开发者

Add new node to xml tree

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

This code generate follow xml tree:

<Root>
  <sub0>
    <subsub0 />
    <subsub0 />
  </sub0>
  <sub1>
    <subsub1 />
    <subsub1 />
  </sub1>
  <sub2>
    <subsub2 />
    <subsub2 />
  </sub2>
  <sub8>
    <subsub123 />
  </sub8>
<开发者_如何学编程;/Root>

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?


Use:

root.Element("sub1").Add(new XElement("subsub123"));

Basically that's finding the existing sub1 element and adding a new sub-element to it, rather than adding a new sub1 element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜