我想要创建此结构的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")));
每个对象“设备”具有List&lt;&gt; “函数”,如何将“函数”添加到xml ???
答案 0 :(得分:9)
每个对象“设备”具有List&lt;&gt; “函数”,如何将“函数”添加到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>
投射到Select
,然后XElement
构造函数完成其余工作。
答案 1 :(得分: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.