我正在尝试根据几个条件将少量节点插入到我的XML文件中。
这是我的XML
<root>
<child name="abc">
<child name="xyz">
</root>
所以现在我的情况就是这样......
if(root/child[name="xyz"]) insert child2 under that tag
所以我的最终XML看起来应该是这样的
<root>
<child name="abc">
<child name="xyz">
<child2></child2>
</root>
需要程序化帮助来实现这一目标。
答案 0 :(得分:0)
string xml = @"<root>
<child name='abc'></child>
<child name='xyz'></child>
</root>";
XDocument doc = XDocument.Parse(xml); //replace with xml file path
doc.Root
.Elements("child")
.Single(c => (string) c.Attribute("name") == "xyz")
.AddAfterSelf(new XElement("child2", ""));
Console.WriteLine(doc.ToString());
返回
<root>
<child name="abc"></child>
<child name="xyz"></child>
<child2></child2>
</root>