javaxmldomxml-parsingxmlunit

How to determine if two XML files have the same structure even if the tags have different values?


I wish to compare two XML files and determine if they have the same structure i.e. The same type and number of tags with preferably the same attributes. The value of the tags and attributes may be different.

This code detects ALL the differences. Even if the structure is the same but values are different. I want to refine this to detect only the structural differences.

public static List compareXML(Reader source, Reader target) throws
              SAXException, IOException{

    //creating Diff instance to compare two XML files
    Diff xmlDiff = new Diff(source, target);

    //for getting detailed differences between two xml files
    DetailedDiff detailXmlDiff = new DetailedDiff(xmlDiff);

    return detailXmlDiff.getAllDifferences();
}

Solution

  • Try this XSLT 3.0:

    <xsl:mode on-no-match="shallow-copy"/>
    <xsl:template match="text()"/>
    <xsl:template match="@*">
      <xsl:attribute name="name()"/>
    </xsl:template>
    
    <xsl:variable name="doc1">
      <xsl:apply-templates select="doc('one.xml')"/>
    </xsl:variable>
    
    <xsl:variable name="doc2">
      <xsl:apply-templates select="doc('two.xml')"/>
    </xsl:variable>
    
    <xsl:template name="xsl:initial-template">
      <xsl:value-of select="deep-equal($doc1, $doc2)"/>
    </xsl:template>