C#-XML-比较两个节点是否相等

本文介绍了一个用于比较两个XML节点是否相同的方法。此方法通过检查节点名称、属性数量及名称值、子节点数量及其内容来判断两个节点是否一致。适用于需要进行XML数据结构一致性校验的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ExpandedBlockStart.gif代码
 1 public bool compareNode(XmlNode node1, XmlNode node2)
 2         {
 3             XmlNodeList node1ChildNodes = node1.ChildNodes;
 4             XmlNodeList node2ChildNodes = node2.ChildNodes;
 5             XmlAttributeCollection node1Attributes = node1.Attributes;
 6             XmlAttributeCollection node2Attributes = node2.Attributes;
 7 
 8             if (node1.Name == node2.Name && node1ChildNodes.Count == node2ChildNodes.Count)
 9             {
10                 if (node1Attributes == null && node2Attributes != null || node1Attributes != null && node2Attributes == null)
11                 {
12                     return false;
13                 }
14                 else if (node1Attributes != null && node2Attributes != null)
15                 {
16                     if (node1Attributes.Count == node2Attributes.Count)
17                     {
18                         int m = 0;
19                         if (node1Attributes.Count > 0)
20                         {
21                             while (m < node1Attributes.Count && node1Attributes.Item(m).Name == node2Attributes.Item(m).Name && node1Attributes.Item(m).Value == node2Attributes.Item(m).Value)
22                             {
23                                 m++;
24                             }
25                             if (m < node1Attributes.Count)
26                             {
27                                 return false;
28                             }
29                         }
30                     }
31                     else
32                     {
33                         return false;
34                     }
35                 }
36                 if (node1ChildNodes.Count == 0)
37                 {
38                     if (node1.InnerText != node2.InnerText)
39                     {
40                         return false;
41                     }
42                 }
43                 else
44                 {
45                     int k = 0;
46                     while (k < node1ChildNodes.Count && compareNode(node1ChildNodes.Item(k), node2ChildNodes.Item(k)))
47                     {
48                         k++;
49                     }
50                     if (k < node1ChildNodes.Count)
51                     {
52                         return false;
53                     }
54                 }
55                 return true;
56             }
57             else
58             {
59                 return false;
60             }
61         }

 

转载于:https://www.cnblogs.com/stli/archive/2010/06/14/1758194.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值