【问题标题】:C# How to use Linq on an XmlAttributeCollection within another Linq statement?C# 如何在另一个 Linq 语句中的 XmlAttributeCollection 上使用 Linq?
【发布时间】:2018-07-06 09:14:33
【问题描述】:

我有一个带有如下子元素的 XML 元素:

<Groups>
    <Group1 name="first" value="1" />
    <Group2 value="2" name="second" />
    <Group3 value="3" />
</Groups>

我正在使用一个已经存在的方法MyMethod() 来获取Groups 元素,该元素返回一个XmlNodeList 对象,我将其转换为XmlNode。之后,我想使用 Linq 语句仅获取那些具有 name 属性的组,并将这些名称存储在字符串列表中。

在下面的代码 sn-p 中,我试图检查 XML 节点的第一个属性名称是否等于 "name",但 "name" 属性可能并不总是第一个。您能否在这里帮助我并告诉我如何在下面的Attributes 属性上使用另一个 Linq 语句? Attributes 属性的类型为 XmlAttributeCollection

List<string> result = MyMethod().Cast<XmlNode>()
    .Where(node => node.Attributes[0].Name == "name")
    .Select(node => node.Attributes[0].Value).ToList();

编辑: 我设法使用内置方法GetNamedItem找到了解决方案:

List<string> result = MyMethod().Cast<XmlNode>()
    .Where(node => node.Attributes?.GetNamedItem("name") != null)
    .Select(node => node.Attributes?.GetNamedItem("name").Value).ToList();

【问题讨论】:

  • 你可以试试这样的: var groups = groups.Where(c => c.Elements().Count(b => b.Attribute("name") != null) > 0 );仅缺少字符串值列表中的条件。你能给我一个字符串值列表的例子吗?

标签: c# xml linq xmlnode xmlattributecollection


【解决方案1】:

您对此有何看法:

List<string> result = MyMethod().Cast<XmlNode>()
    .SelectMany(node => node.Attributes).Where(a => a.Name == "name");

应该与你的目标相匹配,以获取具有特定名称的对象,完整代码变为:

List<string> result = MyMethod().Cast<XmlNode>()
        .SelectMany(node => node.Attributes).Where(a => a.Name == "name")
        .Select(a=> a.Value).ToList();

【讨论】:

    【解决方案2】:

    您问题的关键方法是扩展方法.SelectMany,它从集合集合返回扁平集合。

    作为替代方案,您可以使用 LINQ to XML(听起来像是适合这项工作的工具;))

    var document = XDocument.Load("pathToXmlFile");
    
    // Here you can use more complex logic of "MyMehthod" 
    var allGroups = document.Descendants("Groups");
    
    var names = allGroups.SelectMany(groups => groups.Elements())
                         .Where(group => group.Attribute("name"))
                         .Where(attribute => attribute != null)
                         .Select(attribute => attribute.Value)
                         .ToList();
    

    【讨论】:

    • 感谢您的澄清。不幸的是,我无法修改MyMethod(),因为它已在多个地方使用。但我设法使用GetNamedItem("name") 内置方法找到了另一个解决方案。
    猜你喜欢
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    相关资源
    最近更新 更多