【发布时间】:2020-05-15 11:24:20
【问题描述】:
我需要将我的现有节点列表转换为字符串,以便检查它是否在断言中包含 xml cmets。
这是我的 xml:
<document>
<org1>
<!---- I am a comment ----->
<somenNode1> hello </somenode1>
<somenNode2> hello </somenode1>
</org1>
</document>
我在 NodeList 中,需要转换成字符串,以便检查它是否包含注释。
这是我的代码
public static NodeList allNodes (final Node document, final String xPath) {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
final NodeList result;
try {
final XPathExpression productXpath = xpath.compile(xPath);
result = (NodeList)productXpath.evaluate(document, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
return result;
}
private static void verifyXpathContains (final String expected, final String xPath, org.w3c.dom.Document xmlDoc) {
NodeList nodeList = XPathUtils.allNodes(xmlDoc, xPath);
assertThat(nodeList.toString()).contains(expected);
}
【问题讨论】:
-
最好使用
getNodeType()并与COMMENT_NODE进行比较
标签: java xml xpath xmldocument nodelist