Comparing XML by nodes names and attributes names in C#

前端 未结 1 1604
天命终不由人
天命终不由人 2020-12-22 09:44

I want to compare two (or more) XMLs files by tags names and attributes names. I`m not interested by values of attributes or nodes.

Searching on google i found XMLDi

相关标签:
1条回答
  • 2020-12-22 10:22

    Well if you'd like to do this "manually" an idea would be to use a recursive function and loop through the xml structure. Here is a quick example:

    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());
    

    This is your recursive function:

    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;
    }
    

    Please keep in mind that this will only return true as long as the nodes and attributes are in the same order, and same casing is used on both xml files. You can enhance it to include or exclude attributes/nodes.

    Hope it helps!

    0 讨论(0)
提交回复
热议问题