2012-02-28 10 views
5

どのように私はLinqを使用してこのXMLを逆シリアル化できますか? は、私はあなたがLINQを使用してそれを行うだろうか相続人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クラスを定義しましたか?これまでに何を試しましたか? –

+0

'System.Xml.Serialization.XmlSerializer'を使用する以外の理由はありますか? –

+0

私はXMLにLinqを使用しようとしています – user829174

答えて

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

を作成したいです。明らかに、独自のエラーチェックを行う必要があります。

+0

私は何か似たようなことをしていますが、このコードは最初の要素を返します...リストではありませんか? – cbutler

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

そして、LINQメソッド構文で上記の回答

子孫表示Scott Hanselman

0

からXMLからの変換を行うことについて少し:

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 
}); 
関連する問題