编辑该示例使用包含在 DOM 的 Java 运行时 API 中的 Xerces 解析器。对于 JDOM2 解决方案,请参阅 rolfl 的答案。
作为起点,您可以使用以下代码段。基于你真正想要实现的改变需要你自己来完成。
xml = "<parent xml:space=\"preserve\">\n"
+ "Hello, my name is\n"
+ " <variable type=\"firstname\">ABC</variable>\n"
+ "and my last name is \n"
+ " <variable type=\"lastname\">XYZ</variable>\n"
+ "</parent>";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.compile("//parent").evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getTextContent());
}
输出
Hello, my name is
ABC
and my last name is
XYZ
note片段未优化。更多地将其视为 PoC。