2012-02-28 37 views
5

Làm thế nào tôi có thể deserialize xml này bằng cách sử dụng LINQ? Tôi muốn tạo List<Step>Làm thế nào để deserialize xml bằng cách sử dụng LINQ?

<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

Danh sách những gì? Bạn đã xác định lớp Danh sách của riêng mình chưa? Bạn đã thử những gì cho đến nay? –

+0

Bất kỳ lý do nào để sử dụng không chỉ sử dụng 'System.Xml.Serialization.XmlSerializer'? –

+0

Tôi đang cố gắng sử dụng LINQ để xml không thành công – user829174

Trả lời

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

Heres làm thế nào bạn sẽ làm điều đó bằng cách dùng LINQ. Rõ ràng bạn nên làm kiểm tra lỗi của riêng bạn.

+0

Tôi đang làm điều gì đó tương tự nhưng mã này chỉ trả về phần tử đầu tiên ... không phải là danh sách? – cbutler

4

LINQ-to-XML là câu trả lời của bạn.

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

Và một chút thông tin về làm chuyển đổi từ XML từ Scott Hanselman

0

Hiển thị các câu trả lời trên trong cú pháp phương pháp LINQ

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 
}); 
Các vấn đề liên quan