2012-01-05 66 views
0

基本上我有一個單獨的元素在一個xml文件中,我存儲了我的應用程序的設置。這個元素鏡像了我建立的類。我正在嘗試使用LINQ,選擇該單個元素,然後將存儲在該元素內部的值存儲到我的類的一個實例中。如何使用linq從xml文件中的單個項目創建對象?

現在我單獨選擇元素,然後將該元素的值存儲到不同的屬性中。當然這會變成大約六個單獨的陳述。是否有可能在一個聲明中做到這一點?

回答

2

這將是更好,如果你能證明你的XML,但你可以得到以下

XDocument doc = //load xml document here 

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

您可以使用LINQ到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/en-us/library/bb387098.aspx瞭解更多詳情。

相關問題