简体   繁体   English

使用xdocument创建xml

[英]Creating xml with xdocument

I want create xml file of this structure: 我想创建这个结构的xml文件:

 <Devices>
   <Device Number="58" Name="Default Device" >
     <Functions>
         <Function Number="1" Name="Default func" />
         <Function Number="2" Name="Default func2" />
         <Function Number="..." Name="...." />
     </Functions>
   </Device>
 </Devices>

Here's my code: 这是我的代码:

document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions")));

Each object "device" have List<> of "functions", how can i add "functions" to xml??? 每个对象“设备”都有“函数”的List <>,如何将“函数”添加到xml ???

Each object "device" have List<> of "functions", how can i add "functions" to xml??? 每个对象“设备”都有“函数”的List <>,如何将“函数”添加到xml ???

Really easily - LINQ to XML makes this a doddle: 非常简单 - LINQ to XML使这个变得轻而易举:

document.Element("Devices").Add(
    new XElement("Device",
       new XAttribute("Number", ID),
       new XAttribute("Name", Name),
       new XElement("Functions",
           functions.Select(f => 
               new XElement("Function",
                   new XAttribute("Number", f.ID),
                   new XAttribute("Name", f.Name))))));

In other words, you just project your List<Function> to an IEnumerable<XElement> using Select , and the XElement constructor does the rest. 换句话说,您只需使用SelectList<Function>投影到IEnumerable<XElement> ,然后XElement构造函数完成剩下的工作。

document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions", from f in functions select new XElement("Function", new XAttribute("Number", f.Number), new XAttribute("Name", f.Name)))));

functions would be your list of functions.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM