在C#中按节点名称和属性名称比较XML

我想通过标签名称和属性名称比较两个(或更多)XML文件。 我对属性或节点的值不感兴趣。

在谷歌搜索我发现XMLDiff补丁( http://msdn.microsoft.com/en-us/library/aa302294.aspx ),但它对我不起作用…或者我不知道如何使设置工作为了我。 档案A.

   1 1  TEST   1 A test   2 
20110910
B test

档案B.

    4 1  TEST7   1 A test   2 
20110910
B test

这两个文件必须等于。

谢谢!

好吧,如果你想“手动”这样做,一个想法是使用递归函数并循环遍历xml结构。 这是一个简单的例子:

 var xmlFileA = //first xml var xmlFileb = // second xml var docA = new XmlDocument(); var docB = new XmlDocument(); docA.LoadXml(xmlFileA); docB.LoadXml(xmlFileb); var isDifferent = HaveDiferentStructure(docA.ChildNodes, docB.ChildNodes); Console.WriteLine("----->>> isDifferent: " + isDifferent.ToString()); 

这是你的递归函数:

 private bool HaveDiferentStructure( XmlNodeList xmlNodeListA, XmlNodeList xmlNodeListB) { if(xmlNodeListA.Count != xmlNodeListB.Count) return true; for(var i=0; i < xmlNodeListA.Count; i++) { var nodeA = xmlNodeListA[i]; var nodeB = xmlNodeListB[i]; if (nodeA.Attributes == null) { if (nodeB.Attributes != null) return true; else continue; } if(nodeA.Attributes.Count != nodeB.Attributes.Count || nodeA.Name != nodeB.Name) return true; for(var j=0; j < nodeA.Attributes.Count; j++) { var attrA = nodeA.Attributes[j]; var attrB = nodeB.Attributes[j]; if (attrA.Name != attrB.Name) return true; } if (nodeA.HasChildNodes && nodeB.HasChildNodes) { return HaveDiferentStructure(nodeA.ChildNodes, nodeB.ChildNodes); } else { return true; } } return false; } 

请记住,只有节点和属性的顺序相同,并且两个xml文件都使用相同的大小写时,才会返回true。 您可以对其进行增强以包含或排除属性/节点。

希望能帮助到你!