簡體   English   中英

如何使用linq從xml文件的單個項目創建對象?

[英]How to create an object from a single item from an xml file using linq?

基本上,我在xml文件中只有一個元素,用於存儲應用程序的設置。 這個元素反映了我建立的一個類。 我要使用LINQ進行的操作是選擇單個元素,然后在單個語句中將存儲在該元素內部的值存儲到類的實例中。

現在,我要分別選擇元素,然后將元素中的值存儲到不同的屬性中。 當然,這變成了大約六個單獨的語句。 是否可以在單個語句中執行此操作?

如果可以顯示您的XML,但可以從下面的代碼中獲得一般性的想法會更好。

XDocument doc = //load xml document here

var instance = from item in doc.Descendants("ElementName")
                   select new YourClass()
                              {
                                  //fill the properties using item 
                              };

您可以使用LINQ to XML,例如

var document = XDocument.Load("myxml.xml");
document.Element("rootElement").Element("myElement").Select(e => 
  new MySettingsClass
  {
    MyProperty = e.Attribute("myattribute").Value,
    MyOtherProperty = e.Attribute("myotherattribute").Value 
  });

有關更多詳細信息,請參見http://msdn.microsoft.com/zh-cn/library/bb387098.aspx

暫無
暫無

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

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