将新节点添加到xml树 [英] Add new node to xml tree
本文介绍了将新节点添加到xml树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在生成一个xml树:
I am generating a xml tree:
var root = new XElement("Root");
for(int i =0;i<3;i++)
{
var sub0lvl = new XElement(String.Format("sub{0}",i));
root.Add(sub0lvl);
for(int j=0;j<2;j++)
{
sub0lvl.Add(new XElement(String.Format("subsub{0}",i)));
}
}
此代码生成以下xml树:
This code generate follow xml tree:
<Root>
<sub0>
<subsub0 />
<subsub0 />
</sub0>
<sub1>
<subsub1 />
<subsub1 />
</sub1>
<sub2>
<subsub2 />
<subsub2 />
</sub2>
<sub8>
<subsub123 />
</sub8>
</Root>
我想使用类似的代码将新元素添加到sub1节点
And i want to add new element to sub1 node using code like that
root.Add(new XElement("sub1",new XElement("subsub123")));
但是此代码无法正常运行.只是将新的相同节点添加到根.正确的方法是什么?
But this code is not work as i wish. It's just add new same node to root. What is the right way to do that?
推荐答案
使用:
root.Element("sub1").Add(new XElement("subsub123"));
基本上,这是找到现有的 sub1
元素并向其中添加新的子元素,而不是添加新的sub1
元素.
Basically that's finding the existing sub1
element and adding a new sub-element to it, rather than adding a new sub1
element.
这篇关于将新节点添加到xml树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文