我可以找到两个 xml 文件之间的区别,这里是代码
测试XML1.xml
<Root>
<RName>jj</RName>
<RID>55</RID>
<Source>
<Code ID="17">
<Target Name="A">
<Seq name="A_17_Sql" count="10" >
</Seq>
</Target>
</Code>
</Source>
</Root>
测试XML2.xml
<Root>
<RName>jj</RName>
<RID>55</RID>
<Source>
<Code ID="17">
<Target Name="A">
<Seq name="A_17_Sql" count="9" >
</Seq>
</Target>
</Code>
</Source>
</Root>
Java代码:
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.XMLUnit;
import org.xml.sax.SAXException;
// reading two xml file to compare in Java program
FileInputStream fis1 = new FileInputStream("TestXML1.xml");
FileInputStream fis2 = new FileInputStream("TestXML2.xml");
// using BufferedReader for improved performance
BufferedReader source = new BufferedReader(new InputStreamReader(fis1));
BufferedReader target = new BufferedReader(new InputStreamReader(fis2));
//configuring XMLUnit to ignore white spaces
XMLUnit.setIgnoreWhitespace(true);
//comparing two XML using XMLUnit in Java
List differences = compareXML(source, target);
//showing differences found in two xml files
printDifferences(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();
}
public static void printDifferences(List<Difference> differences){
int totalDifferences = differences.size();
System.out.println("===============================");
System.out.println("Total differences : " + totalDifferences);
System.out.println("================================");
for(Difference difference : differences){
System.out.println(difference.getControlNodeDetail().getXpathLocation());
System.out.println(difference);
}
}
输出 :
===============================
Total differences : 1
================================
/Root[1]/Source[1]/Code[1]/Target[1]/Seq[1]/@count
Expected attribute value '10' but was '9' - comparing <Seq count="10"...> at /Root[1]/Source[1]/Code[1]/Target[1]/Seq[1]/@count to <Seq count="9"...> at /Root[1]/Source[1]/Code[1]/Target[1]/Seq[1]/@count
这种比较工作正常,但我需要显示 attr 名称而不是索引值,如下所示,
===============================
Total differences : 1
================================
/Root[1]/Source[1]/Code[ID=17]/Target[Name=A]/Seq[1]/@count
Expected attribute value '10' but was '9' - comparing <Seq count="10"...> at /Root[1]/Source[1]/Code[ID=17]/Target[Name=A]/Seq[1]/@count to <Seq count="9"...> at /Root[1]/Source[1]/Code[ID=17]/Target[Name=A]/Seq[1]/@count
我们可以像上面那样使用 XMLUnit 吗?