Linq到XML查询涉及属性

时间:2012-03-13 18:05:15

标签: xml linq

我有以下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 for中每个文档的Document类对象 类型属性名称为“b”的帐户值和类型值到类

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

我不确定如何迭代这些类型,或者你是否可以比谓词更整洁

由于 标记

1 个答案:

答案 0 :(得分: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 };