How to deserialize xml using Linq?

后端 未结 3 1175
梦谈多话
梦谈多话 2020-12-06 13:18

How can i deserialize this xml using Linq? I want to create List


  
    1
    

        
相关标签:
3条回答
  • 2020-12-06 14:03
    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();
    

    Heres how you would do it using LINQ. Obviously you should be doing your own error checking.

    0 讨论(0)
  • 2020-12-06 14:04

    Showing the above answers in LINQ method syntax

    Descendants:

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

    Elements:

    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
    });
    
    0 讨论(0)
  • 2020-12-06 14:06

    LINQ-to-XML is your answer.

    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();
    

    And a bit about doing the conversions from XML from Scott Hanselman

    0 讨论(0)
提交回复
热议问题