我的测试失败了:
@Test
@SneakyThrows
public void testSimpleNsXpath() {
String str = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><body xmlns=\"\"><h1>aaa</h1></body></html>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(str));
Document doc = db.parse(is);
XPath xpath = XPathFactory.newInstance().newXPath();
Node node = (Node) xpath.compile("/html[1]/body[1]/h1[1]").evaluate(doc, XPathConstants.NODE);
assertEquals("aaa", node.getTextContent());
}
如果我删除xmlns测试工作,我在节点中得到null。
如何修复我的考试?我想找到h1节点。