如何使用Linq反序列化xml?

时间:2012-02-28 15:50:01

标签: c# xml linq

如何使用Linq对此xml进行反序列化? 我想创建List<Step>

<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>

3 个答案:

答案 0 :(得分: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来做到这一点。显然你应该做自己的错误检查。

答案 1 :(得分: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

进行XML转换

答案 2 :(得分:1)

以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
});