我想比较PUT Request XML
和GET Response XML
。以下代码工作得很好,但根据要求,某些元素只能读取,因此出现在GET Response XML文件中。如何消除以下结果?
结果:
[different] Expected presence of child node 'null' but was 'bs:key_id' - comparing at null to <bs:key_id...> at /container[1]/int_user_object[1]/attributes[1]/key_id[1]
我尝试了什么:
import java.io.IOException;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.xml.sax.SAXException;
public class XMLComparator {
static Logger logger = LogManager.getLogger(XMLComparator.class);
public boolean compare(String xml1, String xml2) throws SAXException, IOException {
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreComments(true);
XMLUnit.setIgnoreAttributeOrder(true);
DetailedDiff diff = new DetailedDiff(new Diff(xml1, xml2)); // wrap the Diff inside Detailed Diff.
List<?> allDiff = diff.getAllDifferences();
boolean result = diff.similar();
if (result == false) {
logger.info("There are " + allDiff.size() + " differences. XML difference(s): " + diff.toString());
} else {
logger.info("Sending XML and received XML are same: " + result);
}
return result;
}
}
我计划在阅读本文doc后在我的代码中添加这样的逻辑,但我不能。
if(NODE_TYPE_ID == null){
difference.ignore();}
根据Stefan的帮助,您可以看到我的代码的最新版本
修改
public class XMLComparator {
static Logger logger = LogManager.getLogger(XMLComparator.class);
public boolean compare(String xml1, String xml2) throws SAXException, IOException {
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreComments(true);
XMLUnit.setIgnoreAttributeOrder(true);
DetailedDiff diff = new DetailedDiff(new Diff(xml1, xml2));
diff.overrideDifferenceListener(new DifferenceListener() {
@Override
/* CHILD_NODE_NOT_FOUND_ID is used: A child node in one piece of XML could not be match against any other node of the other piece.
*
*/
public int differenceFound(Difference difference) {
return difference.getId() == DifferenceConstants.CHILD_NODE_NOT_FOUND_ID
? RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL : RETURN_ACCEPT_DIFFERENCE;
}
@Override
public void skippedComparison(Node arg0, Node arg1) {
}
});
List<?> allDiff = diff.getAllDifferences();
boolean result = diff.identical();
if (result == false) {
logger.info("There are " + allDiff.size() + " differences. XML difference(s): " + diff.toString());
} else {
logger.info("Sending XML and received XML are same: " + result);
}
return result;
}
}
答案 0 :(得分:1)
一种方法是实现DifferenceListener
并抑制由于缺少节点而产生的差异,例如
public int differenceFound(Difference difference) {
return difference.getId() == DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID
? RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL
: RETURN_ACCEPT_DIFFERENCE;
}
但是,如果您可以选择切换到XMLUnit 2.x,则可以使用NodeFilter
来完全隐藏您知道丢失的元素(而不是忽略所有缺少的元素)。