我有2个xml文件,结构几乎相似,在这些XML文件中如何获取以下信息?
为了您的信息,我尝试了以下代码:
File f1 = new File(inputXMLPath);
File f2= new File(outputXMLPath);
FileReader fr1 = null;
FileReader fr2 = null;
try {
fr1 = new FileReader(f1);
fr2 = new FileReader(f2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
Diff diff = new Diff(fr1, fr2);
System.out.println("Similar? " + diff.similar());
System.out.println("Identical? " + diff.identical());
DetailedDiff detDiff = new DetailedDiff(diff);
detDiff.overrideDifferenceListener(new DifferenceListener() {
@Override
public int differenceFound(Difference diff) {
if (diff.getId() == DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID
|| diff.getId() == DifferenceConstants.CHILD_NODELIST_LENGTH_ID) {
return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
return RETURN_ACCEPT_DIFFERENCE;
}
@Override
public void skippedComparison(Node arg0, Node arg1) { }
});
List differences = detDiff.getAllDifferences();
for (Object object : differences) {
Difference difference = (Difference)object;
System.out.println("***********************");
System.out.println(difference);
System.out.println("***********************");
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:1)
[编辑:添加了关于setCompareUnmatched
和示例代码的说明]
我想您希望对{1}} CHILD_NODE_NOT_FOUND
做出反应,如果您使用Difference
,XMLUnit 1.x将会发出这些内容。
如果XMLUnit.setCompareUnmatched(false)
的控制节点为空,则添加节点 - 如果测试节点为空,则删除该节点。任何其他差异都是对XMLUnit认为存在于任何一方的节点的更改。
例如
Difference
会导致类似
的内容 FileReader fr1 = new FileReader(f1);
FileReader fr2 = new FileReader(f2);
XMLUnit.setCompareUnmatched(false);
Diff diff = new Diff(fr1, fr2);
System.out.println("Similar? " + diff.similar());
System.out.println("Identical? " + diff.identical());
DetailedDiff detDiff = new DetailedDiff(diff);
detDiff.overrideDifferenceListener(new DifferenceListener() {
@Override
public int differenceFound(Difference diff) {
if (diff.getId() == DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID
|| diff.getId() == DifferenceConstants.CHILD_NODELIST_LENGTH_ID) {
return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
return RETURN_ACCEPT_DIFFERENCE;
}
@Override
public void skippedComparison(Node arg0, Node arg1) { }
});
List differences = detDiff.getAllDifferences();
for (Object object : differences) {
Difference difference = (Difference)object;
System.out.println("***********************");
if (difference.getId() == DifferenceConstants.CHILD_NODE_NOT_FOUND_ID) {
if (difference.getControlNodeDetail().getNode() == null) {
System.out.println("Node was added");
} else {
System.out.println("Node was removed");
}
}
System.out.println("***********************");
}