0

我想通过在现有 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>
4

1 回答 1

1

I find Linq To Xml easier to use.

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();

EDIT

And a hybrid code :)

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");
于 2013-09-11T11:57:50.663 回答