【发布时间】:2016-12-20 14:12:54
【问题描述】:
我正在尝试比较 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;
}
}
【问题讨论】: