2

我想创建这个结构的 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>

这是我的代码:

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

每个对象“设备”都有“功能”列表<>,我怎样才能将“功能”添加到 xml?

4

2 回答 2

9

每个对象“设备”都有“功能”列表<>,我怎样才能将“功能”添加到 xml?

真的很容易 - 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))))));

换句话说,您只需将您的投影List<Function>IEnumerable<XElement>using SelectXElement其余的由构造函数完成。

于 2012-08-06T15:54:43.533 回答
1
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.
于 2012-08-06T15:57:17.497 回答