的XElement =>添加子节点在运行时 [英] XElement => Add children nodes at run time

查看:162
本文介绍了的XElement =>添加子节点在运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,让我们假设这是我想要实现:

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>



不知道如果使用的XElement是最简单的方法结果
,而这是我迄今为止:

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

现在我来补充基于一些数据我有孩子。结果
有可能是1,2,3,4 ...

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



问题:



这样做的方式,我将缺少儿童父节点
。如果我只是在foreach之前添加它,它会呈现为一个封闭的节点

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/>

这不是我们想要的。

我如何可以添加到第1部分父节点和多达我的列表中有

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

推荐答案

试试这个:

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

这篇关于的XElement =&GT;添加子节点在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆