我有一个示例XML,如下所示:
<message>
<metadata>
<msg_id>1</msg_id>
<client_type>type1</client_type>
</metadata>
<individual>
<name>John</name>
<surname>Smith</surname>
<additional_information>
<e_mail>[email protected]</e_mail>
<phone_number>11110000</phone_number>
</additional_information>
</individual>
</message>
我的目标是获取输出,该输出将向我显示每个元素XML的路径,如下所示:
/message/metadata/msg_id
/message/metadata/client_type
/message/individual/name
等等。我该如何用Java处理呢?
提前非常感谢您的任何提示!
您可以使用xPath通过表达式选择节点并打印每个节点的路径,
这是Java代码:
public static void main(String[] args) throws Exception {
File file = new File("src/main/resources/file.xml");
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//*[not(*)]";
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(file);
document.getDocumentElement().normalize();
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
for(int i = 0 ; i < nodeList.getLength(); i++) {
System.out.println(getXPath(nodeList.item(i)));
}
}
private static String getXPath(Node node) {
Node parent = node.getParentNode();
if (parent == null) {
return node.getNodeName();
}
return getXPath(parent) + "/" + node.getNodeName();
}
最终输出为:
文档/消息/元数据/ msg_id
文档/消息/元数据/ client_type
文件/信息/个人/名称
文件/讯息/个人/姓氏
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句