2012-02-28 49 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 
});