2012-02-28 72 views
5

我該如何反序列化這個使用Linq的XML? 我想創建List<Step>如何使用Linq反序列化xml?

<MySteps> 
    <Step> 
    <ID>1</ID> 
    <Name>Step 1</Name> 
    <Description>Step 1 Description</Description> 
    </Step> 
    <Step> 
    <ID>2</ID> 
    <Name>Step 2</Name> 
    <Description>Step 2 Description</Description> 
    </Step> 
    <Step> 
    <ID>3</ID> 
    <Name>Step 3</Name> 
    <Description>Step 3 Description</Description> 
    </Step> 
    <Step> 
    <ID>4</ID> 
    <Name>Step 4</Name> 
    <Description>Step 4 Description</Description> 
    </Step> 
</MySteps> 
+0

什麼是什麼?你有沒有定義自己的List類?你試過什麼了? – 2012-02-28 15:50:55

+0

不只是使用'System.Xml.Serialization.XmlSerializer'的任何理由? – 2012-02-28 15:56:16

+0

我正在嘗試使用Linq到xml沒有成功 – user829174 2012-02-28 15:57:52

回答

12
string xml = @"<MySteps> 
       <Step> 
        <ID>1</ID> 
        <Name>Step 1</Name> 
        <Description>Step 1 Description</Description> 
       </Step> 
       <Step> 
        <ID>2</ID> 
        <Name>Step 2</Name> 
        <Description>Step 2 Description</Description> 
       </Step> 
       <Step> 
        <ID>3</ID> 
        <Name>Step 3</Name> 
        <Description>Step 3 Description</Description> 
       </Step> 
       <Step> 
        <ID>4</ID> 
        <Name>Step 4</Name> 
        <Description>Step 4 Description</Description> 
       </Step> 
       </MySteps>"; 

XDocument doc = XDocument.Parse(xml); 

var mySteps = (from s in doc.Descendants("Step") 
       select new 
       { 
        Id = int.Parse(s.Element("ID").Value), 
        Name = s.Element("Name").Value, 
        Description = s.Element("Description").Value 
       }).ToList(); 

繼承人你會怎麼使用LINQ做到這一點。顯然你應該做自己的錯誤檢查。

+0

我正在做類似的事情,但這段代碼只返回第一個元素...不是列表? – cbutler 2017-07-05 22:29:03

4

LINQ-to-XML是你的答案。

List<Step> steps = (from step in xml.Elements("Step") 
        select new Step() 
        { 
         Id = (int)step.Element("Id"), 
         Name = (string)step.Element("Name"), 
         Description = (string)step.Element("Description") 
        }).ToList(); 

而且一些有關從Scott Hanselman

0

做從XML的轉換顯示在LINQ方法語法上述答案

後人:

var steps = xml.Descendants("Step").Select(step => new 
{ 
    Id = (int)step.Element("ID"), 
    Name = step.Element("Name").Value, 
    Description = step.Element("Description").Value 
}); 

元素:

var steps2 = xml.Element("MySteps").Elements("Step").Select(step => new 
{ 
    Id = (int)step.Element("ID"), 
    Name = step.Element("Name").Value, 
    Description = step.Element("Description").Value 
});