【发布时间】:2017-05-13 01:15:58
【问题描述】:
我目前正在处理一个由多个 XML 文件组成的 XML 字符串(所有 xml 数据都存储在 String 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 中检索“所有者”的所有值,但我的代码显然只在有一个 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 文件的情况下,我仍然可以检索所有“所有者”值并将它们存储在类似 String owner[] 之类的东西中?
非常感谢您的帮助!
【问题讨论】:
-
我不知道在java中如何处理,但是添加一个封装所有的标签呢?所以在文件的开头添加一个标签,如
<globaltag>,并在文件的末尾添加一个标签,如</globaltag> -
@eLRuLL 出于某种原因,这个技巧在 ruby 中有效,但在 java 中无效。很奇怪吧?
-
也许java中还有另一个xml解析器?抱歉,我无法提供更多帮助。当前的 xmlparser 似乎正在搜索第一个
<?xml及其结束标记 -
@eLRuLL 感谢您的建议。我认为将字符串分成多个可能是这里最安全的选择。
-
我认为您不接受我的回答是有原因的。介意分享吗?通常,当人们不接受时,他们会收到更多有用的意见;但我在这里看不到...