【问题标题】:C# Iterate and Compare multiple nodesC#迭代和比较多个节点
【发布时间】:2018-12-20 09:39:39
【问题描述】:

我有一个 XML 文件,我需要遍历 XML 文件并比较节点属性值。条件是节点的元素中的属性应该有一个特定的值集。

让我通过下面的示例让这更容易理解:

<Node name="SomeName">
<Element attribute="somevalue"/>
</Node>
<Node name="SomeNameMore">
 <Element attribute="somevalue"/>
</Node>
<Node name="SomeNameEtc.">
 <Element attribute="somevaluenotmatch"/>
</Node>
<Node name="SomeName">
 <Element attribute="somevalue"/>
</Node>

XML 文件中有 100 个相似的节点。

第一个条件:匹配属性'somevalue'

第2个条件:比较第1个条件(结果)中的所有节点以获取节点中的属性名称。

我做了如下:

        XmlTextReader Reader = new XmlTextReader("C:\\TEST\test.xml");
        XmlDocument doc = new XmlDocument();
        doc.Load(Reader);

        XPathNavigator nav = doc.CreateNavigator();
        XmlElement rootNode = doc.DocumentElement;

        XPathExpression expr;

        expr = nav.Compile("//Element[@attribute='somevalue']");
        XPathNodeIterator iterator = nav.Select(expr);

        foreach (XmlElement item in iterator)
        {
          //how do go back to node here (whose element has attribute 'somevalue' and compare with the next node if the attribute 'name' of Node matches
          } ;

【问题讨论】:

  • 表示你想检索所有Element与somevalue具有相同值匹配的Nodes,对吧?
  • 是的,这是正确的,然后在提取的数据中比较节点的属性“名称”。

标签: c# xml xpath


【解决方案1】:

使用 xml linq 可以轻松创建所需值的字典

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication93
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);
            Dictionary<string, string> dict = doc.Descendants("Node")
                .GroupBy(x => (string)x.Attribute("name"), y => (string)y.Element("Element").Attribute("attribute"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            //or if you have multiple items with same key
            Dictionary<string, List<string>> dict2 = doc.Descendants("Node")
                .GroupBy(x => (string)x.Attribute("name"), y => (string)y.Element("Element").Attribute("attribute"))
                .ToDictionary(x => x.Key, y => y.ToList());

        }

    }


}

【讨论】:

    【解决方案2】:

    您可以使用 linq 来执行您正在寻找的事情,我不确定我是否正确理解了第二种情况,但我将分享第一种情况的示例,它可能会帮助您找到做事的好方法它:

    var xml = XDocument.Load("your_xmlFile_path");
    var query = from c in xml.Root.Descendants("Node").Descendants("Element")
                where c.Attribute("attribute").Value == "somevalue"
                select c;
    

    我为您测试了查询,它返回正确数量的“somevalue”元素。

    编辑 您可以通过替换

    来检索属性的名称而不是值
    c.Attribute("attribute").Value
    

    由

    c.Attribute("attribute").Name
    

    希望对你有帮助,祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      • 2015-01-07
      • 2017-05-02
      • 1970-01-01
      • 2012-10-24
      • 2012-11-05
      • 2021-03-07
      相关资源
      最近更新 更多