以下是一个比较两个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("- 1
- 2
");
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml("- 1
- 3
");
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
方法来比较这两个列表。