java - 在Java中使用xpath解析由多个xml文件组成的xml字符串

标签 java xml parsing xpath

我当前正在使用一个 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/

相关文章:

java - 版本控制 REST API 和供应商特定的内容类型

java - 创建一个我可以将二进制文件发送到的 RESTful 服务是否有意义?

android - 具有自定义 XML 布局的按钮

parsing - 允许多次读取 http.Request.Body 的正确方法是什么

java - 映射<S,S> 到列表<S>

java - 用于 tomcat 的分布式 HTTP session 状态服务器

iOS - 无法让 SMS XMLDocument 工作

c# - 通过 API 提要在 C# 中提取 XML 元素

javascript - 将 innerhtml 拆分为文本以在 javascript 中翻译 JSON

parsing - 是否有一种既定的方法来编写可以重建其确切输入的解析器?