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に「関数」を追加するにはどうすればよいですか?

本当に簡単です-LINQtoXMLは、これを簡単にします。

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

つまり、usingにプロジェクトを投影するだけでList<Function>IEnumerable<XElement>残り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 に答える