【问题标题】:Linq to XML query involving attributes涉及属性的 Linq to XML 查询
【发布时间】:2012-03-14 02:08:35
【问题描述】:

我有以下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; }
}

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

谢谢 标记

【问题讨论】:

    标签: xml linq


    【解决方案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 };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多