如何使用Linq反序列化xml

本文关键字:xml 反序列化 Linq 何使用 | 更新日期: 2023-09-27 18:26:12

如何使用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>

如何使用Linq反序列化xml

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的方法。显然,你应该自己检查错误。

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转换的内容

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