我当前正在使用一个 XML 字符串(存储在 String xml 中的所有 xml 数据),该字符串由以下格式的多个 XML 文件组成:
<?xml version...>
<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 version...>
<File xml:space="preserve">
<Subfile keyword="Store" tag="0">
<Value number="1">Walmart</Value>
</Subfile>
<Subfile keyword="Owner" tag="1">
<Value number="1">Eliza Calvin</Value>
</Subfile>
<Subfile keyword="Date" tag="2">
<Value number="1">20161130</Value>
</Subfile>
</File>
...
我想从 xml 中检索“Owner”的所有值,但我的代码显然仅在存在一个 xml 文件时才有效。下面是当 xml 字符串中只有一个 xml 文件时我的工作代码:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/File/Subfile[@keyword='Owner']/Value";
String owner = xpath.compile(expression).evaluate(document);
如何修改我的代码,以确保即使在 xml 字符串具有多个 xml 文件的情况下,我仍然可以检索所有“Owner”值并将它们存储在诸如 String Owner[] 之类的内容中?
非常感谢您的帮助!
最佳答案
您的示例显示每个 XML 条目均以以下内容开头
<?xml version...>
所以最简单的方法是使用 String.split()使用该模式;产生一个实际上应该包含不同文件内容的字符串数组。
或者,您可以简单地使用 String.index() 来查找每个 <?...>
的“起始索引”标签;并使用子字符串检索直到下一个“起始索引”的所有内容。
关于java - 在Java中使用xpath解析由多个xml文件组成的xml字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41367402/