簡體   English   中英

使用Xdocument讀取XML

[英]Read XML with Xdocument

我的課:

public class Device
{
     int ID;
     string Name;
     List<Function> Functions;
}

和類功能:

public class Function
{
     int Number;
     string Name;
}

而且我有這種結構的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>

這是代碼,我正在嘗試讀取對象:

  var list = from tmp in document.Element("Devices").Elements("Device")
                       select new Device()
                       {
                           ID = Convert.ToInt32(tmp.Attribute("Number").Value),
                           Name = tmp.Attribute("Name").Value,
                           //??????
                       };
            DevicesList.AddRange(list);

我如何閱讀“功能” ???

使用ElementsSelect將一組元素投影到對象上,再次執行相同的操作。

var list = document
     .Descendants("Device")
     .Select(x => new Device {
                     ID = (int) x.Attribute("Number"),
                     Name = (string) x.Attribute("Name"),
                     Functions = x.Element("Functions")
                                  .Elements("Function")
                                  .Select(f =>
                                      new Function {
                                      Number = (int) f.Attribute("Number"),
                                      Name = (string) f.Attribute("Name")
                                    }).ToList()
                  });

為了清楚起見,我實際上建議在DeviceFunction中分別編寫一個靜態FromXElement方法。 然后,每一段代碼都只能做一件事。 因此,例如, Device.FromXElement可能看起來像這樣:

public static Device FromXElement(XElement element)
{
    return new Device
    {
        ID = (int) element.Attribute("Number"),
        Name = (string) element.Attribute("Name"),
        Functions = element.Element("Functions").Elements("Function")
                         .Select(Function.FromXElement)
                         .ToList();
    };
}

這也使您可以將設置器在類中設為私有,因此它們可以是公共不可變的(在集合中付出了一些努力)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM