2012-03-13 60 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