2

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.