XElement => Add children nodes at run time

◇◆丶佛笑我妖孽 提交于 2019-11-28 20:55:33

问题


So let's assume this is what i want to achieve:

<root>
  <name>AAAA</name>
  <last>BBBB</last>
  <children>
     <child>
        <name>XXX</name>
        <last>TTT</last>
     </child>
     <child>
        <name>OOO</name>
        <last>PPP</last>
     </child>
   </children>
</root>

Not sure if using XElement is the simplest way
but this is what I have so far:

 XElement x = new XElement("root",
                  new XElement("name", "AAA"),
                  new XElement("last", "BBB"));

Now I have to add the "children" based on some data i have.
There could be 1,2,3,4 ...

so I need to iterate thru my list to get every single child

foreach (Children c in family)
{
    x.Add(new XElement("child", 
              new XElement("name", "XXX"),
              new XElement("last", "TTT")); 
} 

PROBLEM:

Doing this way I will be missing the "CHILDREN Parent node". If I just add it before the foreach, it will be rendered as a closed node

<children/>

and that's NOT what we want.

QUESTION:

How can I add to the 1st part a parent node and as many as my list has?


回答1:


Try this:

var x = new XElement("root",
             new XElement("name", "AAA"),
             new XElement("last", "BBB"),
             new XElement("children",
                 from c in family
                 select new XElement("child",
                             new XElement("name", "XXX"),
                             new XElement("last", "TTT")
                        )
             )
        );



回答2:


 XElement root = new XElement("root",
                  new XElement("name", "AAA"),
                  new XElement("last", "BBB"));

XElement children = new XElement("children");

foreach (Children c in family)
{
    children.Add(new XElement("child", 
              new XElement("name", c.Name),
              new XElement("last", c.Last)); 
}
root.Add(children);



回答3:


var children = new XElement("children");
XElement x = new XElement("root",
                  new XElement("name", "AAA"),
                  new XElement("last", "BBB"),
                  children);

foreach (Children c in family)
{
    children.Add(new XElement("child", 
              new XElement("name", "XXX"),
              new XElement("last", "TTT")); 
} 


来源:https://stackoverflow.com/questions/8558763/xelement-add-children-nodes-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!