1

我试图根据几个条件将几个节点插入到我的 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>

需要程序帮助来实现这一目标。

4

1 回答 1

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>
于 2015-01-16T12:52:02.820 回答