【问题标题】:Parse complicated XMLs in weird format using Java使用 Java 以奇怪的格式解析复杂的 XML
【发布时间】:2016-12-27 23:02:21
【问题描述】:

我收到了格式奇怪的 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”的最有效方法是什么?

谢谢。

【问题讨论】:

  • 不解析xml文件就无法获取值。 “Caleb Haldane”发布的内容是实现您的目标的简单方法,尽管它会在内部解析文件。因此,要么您正在寻找一种方法,因此您不必自己解析它(在这种情况下,答案由“Caleb Haldane”给出)。否则就没有办法实现你的目标。
  • 你为什么称之为“奇怪的格式”?在我看来,它就像普通的 XML。
  • @n247s 谢谢。这是有道理的。
  • @ajb 因为原始文件的每个子文件元素都有大约 50 个属性,我觉得这很奇怪。

标签: java xml parsing


【解决方案1】:

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

下面的xpath查找Subfile Nodes的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);

【讨论】:

  • 谢谢。一个澄清虽然。带有“所有者”的行正在给我错误消息。但是当我删除“值”之后的“/”时,错误消失了。这是正确的路径格式吗?
  • @ruby_le 你说得对,我从另一个站点转移了 xpath 语句,忘记修剪它。
  • 为了 Java 的利益,需要对 "Owner" 周围的引号进行转义。我已将它们编辑为单引号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多