gpt4 book ai didi

java - 使用 Java 解析奇怪格式的复杂 XML

转载 作者:行者123 更新时间:2023-12-01 18:00:30 26 4
gpt4 key购买 nike

我收到了格式奇怪的 xml,格式如下:

<File xml:space="preserve">
<Subfile keyword="Store" tag="0">
<Value number="1">Amazon</Value>
</Subfile>
<Subfile keyword="Owner" tag="1">
<Value number="1">Alice Murphy</Value>
</Subfile>
<Subfile keyword="Date" tag="2">
<Value number="1">20161114</Value>
</Subfile>
</File>

在这种情况下,无需解析整个 XML 即可检索值“Alice Murphy”的最有效方法是什么?

谢谢。

最佳答案

可以用xpath解析你想要的节点。

下面的xpath查找子文件节点的Value节点,其中关键字是“Owner”

// parse the XML as a W3C Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new File("<xml path and filename>"));

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/File/Subfile[@keyword='Owner']/Value";
Node ownerNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);

关于java - 使用 Java 解析奇怪格式的复杂 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41353274/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com