如何使用 C# 将子项附加到 xml 中

本文关键字:xml 何使用 | 更新日期: 2023-09-27 18:30:59

我想通过在现有XML中添加下面提到的标签来修改XML:

<filter>
<filterName>FOUND_IN_BUILD</filterName>
<operator>
<name>Equals</name>
</operator>
<value>2</value>
</filter>

我正在尝试使用以下代码:

XmlNode FIB_filter = doc.CreateNode(XmlNodeType.Element, "filter", null);
//XmlNode FIB_filtername = doc.CreateNode(XmlNodeType.Element, "filterName", "FOUND_IN_BUILD");
XmlNode FIB_filtername = doc.CreateElement("filterName");
FIB_filtername.InnerText = ("FOUND_IN_BUILD");
XmlNode FIB_operator = doc.CreateNode(XmlNodeType.Element, "operator", null);
//XmlNode FIB_name = doc.CreateNode(XmlNodeType.Element, "operator", "Equals");
XmlNode FIB_name = doc.CreateElement("operator");
FIB_name.InnerText = ("Equals");
XmlNode FIB_value = doc.CreateNode(XmlNodeType.Element, "value", null);

但我得到以下回应:

<filter>
<filterName>
FOUND_IN_BUILD
<operator>
<operator>
Equals
<value/>
</operator>
</operator>
</filterName>
</filter>

请帮助并建议我执行所需的操作,因为我是 C# 的 xml 功能的新手。

我的初始 XML 如下所示:

<criteria>
        <includeFilterSets>
          <filterSet>
            <filter>
              <filterName>PRODUCT_NAME</filterName>
              <operator>
                <name>Equals</name>
              </operator>
              <value>Dr.Watson</value>
            </filter>
          </filterSet>
        </includeFilterSets>
        <caseSensitive>false</caseSensitive>
        <entityToSearch>
          <name>BUG</name>
        </entityToSearch>
      </criteria>

我正在寻找的响应如下:

<criteria>
<includeFilterSets>
<filterSet>
<filter>
<filterName>PRODUCT_NAME</filterName>
<operator>
<name>Equals</name>
</operator>
<value>Dr.Watson</value>
</filter>
<filter>
<filterName>FOUND_IN_BUILD</filterName>
<operator>
<name>Equals</name>
</operator>
<value>2</value>
</filter>
</filterSet>
</includeFilterSets>
<caseSensitive>false</caseSensitive>
<entityToSearch>
<name>BUG</name>
</entityToSearch>
</criteria>

如何使用 C# 将子项附加到 xml 中

我发现Linq To XML更容易使用。

var xDoc = XDocument.Load(fName);
var filterset = xDoc.Root.Element("includeFilterSets").Element("filterSet");
var filter = new XElement("filter", 
                    new XElement("filterName","FOUND_IN_BUILD"),
                    new XElement("operator",new XElement("name","Equals")),
                    new XElement("value",2)
                    );
filterset.Add(filter);
string newXml = xDoc.ToString();

编辑

和混合代码:)

var filter = new XElement("filter", 
                    new XElement("filterName","FOUND_IN_BUILD"),
                    new XElement("operator",new XElement("name","Equals")),
                    new XElement("value",2)
                    );
XmlDocument doc = new XmlDocument();
doc.Load(fName);
var node = doc.SelectSingleNode("//includeFilterSets/filterSet");
node.CreateNavigator().AppendChild(filter.CreateReader());
doc.Save(fName + ".new.xml");