比较两个xmlNodeList以找出差异
创始人
2024-12-14 17:01:21
0次

以下是一个比较两个XmlNodeList以找出差异的示例代码:

using System;
using System.Xml;

public class XmlUtils
{
    public static void CompareXmlNodeLists(XmlNodeList nodeList1, XmlNodeList nodeList2)
    {
        if (nodeList1.Count != nodeList2.Count)
        {
            Console.WriteLine("The two XmlNodeLists have different lengths.");
            return;
        }

        for (int i = 0; i < nodeList1.Count; i++)
        {
            XmlNode node1 = nodeList1[i];
            XmlNode node2 = nodeList2[i];

            if (!AreNodesEqual(node1, node2))
            {
                Console.WriteLine($"Difference found at index {i}:");
                Console.WriteLine($"Node1: {node1.OuterXml}");
                Console.WriteLine($"Node2: {node2.OuterXml}");
                Console.WriteLine();
            }
        }

        Console.WriteLine("Comparison finished.");
    }

    private static bool AreNodesEqual(XmlNode node1, XmlNode node2)
    {
        if (node1.NodeType != node2.NodeType)
            return false;

        if (node1.NodeType == XmlNodeType.Element)
        {
            if (node1.Name != node2.Name)
                return false;

            if (node1.Attributes?.Count != node2.Attributes?.Count)
                return false;

            if (node1.InnerXml != node2.InnerXml)
                return false;
        }
        else if (node1.NodeType == XmlNodeType.Text)
        {
            if (node1.Value != node2.Value)
                return false;
        }
        
        return true;
    }
}

public class Program
{
    public static void Main()
    {
        XmlDocument doc1 = new XmlDocument();
        doc1.LoadXml("12");

        XmlDocument doc2 = new XmlDocument();
        doc2.LoadXml("13");

        XmlNodeList nodeList1 = doc1.DocumentElement.SelectNodes("item");
        XmlNodeList nodeList2 = doc2.DocumentElement.SelectNodes("item");

        XmlUtils.CompareXmlNodeLists(nodeList1, nodeList2);
    }
}

在上述示例中,我们定义了一个XmlUtils类,其中包含一个CompareXmlNodeLists方法,用于比较两个XmlNodeList对象。该方法首先检查两个列表的长度是否相等,如果不相等,则说明有差异。然后,它遍历两个列表中的每个节点,并使用AreNodesEqual方法比较节点是否相等。如果节点不相等,则打印差异信息。

AreNodesEqual方法用于比较两个节点是否相等。它首先检查节点的类型是否相同,如果不同,则说明节点不相等。对于元素节点,它比较节点的名称、属性数量和内部XML内容是否相等。对于文本节点,它比较节点的值是否相等。

在Main方法中,我们创建了两个XmlDocument对象,并从中选择了item节点的XmlNodeList。然后,我们调用XmlUtils类的CompareXmlNodeLists方法来比较这两个列表。

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...