List<String> targetCollection = new ArrayList<>();
try {
XPath xPath = XPathFactory.newInstance().newXPath();
if ( !namespaceContext.isEmpty() ) {
xPath.setNamespaceContext(new MapNamespaceContext(namespaceContext));
}
XPathExpression expression = xPath.compile("Document");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(!namespaceContext.isEmpty());
Document document = factory.newDocumentBuilder().parse(new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)));
NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
targetCollection.add(nodeToString(nodeList.item(i)));
}
}
catch (SAXException | ParserConfigurationException | XPathExpressionException | IOException e) {
throw new RuntimeException("Cannot split the specified message.");
}
尝试使用上面的代码,但NOdeList为0 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document xmlns="test:123:146">
<A>
<B>
</B>
<C>
<D>
<E></E>
</D>
</C>
</A>
</Document>
(这是一个复杂的xml)调试节点列表为0,文档没有显示xml的所有节点 有什么建议我做错了吗?