我想通过在现有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>
答案 0 :(得分:2)
我发现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");