2012-03-13 59 views
0

我有以下XML的LINQ to XML查詢涉及的屬性

<root> 
<document> 
    <account>12</account> 
    <type name-"a">stuff</type> 
    <type name-"b">stuff</type> 
</document> 
<document> 
    <account>42</account> 
    <type name-"a">stuff</type> 
    <type name-"b">good stuff</type> 
    <type name-"c">good stuff</type> 
</document> 
</root> 

我想使用LINQ to XML對於XML中的每個文檔的Document類對象返回 賬面價值和類型值,其中類型屬性名稱是「b」進級

class Document { 
    public string Account { get; set; } 
    public string BType { get; set; } 
} 

我不知道我怎麼遍歷類型或者是否可以比整潔與謂詞

感謝 馬克

回答

1

喜歡的東西:

var query = doc.Descendants("document") 
      .Where(x => x.Elements("type") 
          .Any(b => (string) b.Attribute("name") == "b")) 
      .Select(x => new Document { 
         Account = (string) x.Element("account") 
         BType = x.Elements("type") 
           .First(b => (string) b.Attribute("name") == "b") 
           .Value 
        }); 

或者:

var query = from d in doc.Descendants("document") 
      let b = d.Elements("type") 
        .FirstOrDefault((string) d.Attribute("name") == "b") 
      where b != null 
      select new Document { Account = (string) d.Element("account"), 
            BType = b.Value }; 
+0

感謝第一個工作一種享受 – 2012-03-13 22:28:40