我想创建这个结构的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>
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions")));
Run Code Online (Sandbox Code Playgroud)
每个对象"设备"都有"函数"的List <>,如何将"函数"添加到xml ???
每个对象"设备"都有"函数"的List <>,如何将"函数"添加到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))))));
Run Code Online (Sandbox Code Playgroud)
换句话说,你只是将你的项目投射List<Function>到一个IEnumerable<XElement>使用Select,XElement构造函数完成其余的工作.