【问题标题】:xpath compile using java - NodeList with particular node valuexpath 编译使用 java - 具有特定节点值的 NodeList
【发布时间】:2023-03-19 23:37:01
【问题描述】:
<data xmlns:fsd="abc.org" xmlns:xlink="http://www.w3.org/1999/xlink">
<meta name="elapsed-time" value="46" />
<org-family>
<family-member id="5">
<publication-reference>
<document-id document-id-type="docdb">
<country>US</country>
<doc-number>3056228</doc-number>
<date>20160817</date>
</document-id>
</publication-reference>
</family-member>
<family-member id="2">
<publication-reference>
<document-id document-id-type="docdb">
<country>US</country>
<doc-number>2013315173</doc-number>
<date>20150430</date>
</document-id>
</publication-reference>
</family-member>
</org-family>
</data>

我想从上面的xml中提取国家和日期节点值,下面是我的java代码

NodeList familyMembers = (NodeList) xPath.compile("//family-member//publication-reference//document-id[@document-id-type=\"docdb\"]//text()").evaluate(xmlDocument,XPathConstants.NODESET);

 ArrayList mainFamily = new ArrayList();
                for (int i = 0; i < familyMembers.getLength(); i++) {
                    mainFamily.add(familyMembers.item(i).getNodeValue());
                }

但它提取所有三个节点值(country, doc-number and date),但我只需要两个节点值(country and date),在 for 循环中我应该如何传递请求的节点值?

【问题讨论】:

  • 这不是一个有效的 XML - &lt;publication-reference&gt;&lt;family-member&gt; 没有关闭,并且没有根元素。
  • 你知道路径表达式中///操作符的区别吗...?见XML Path Language (XPath) – 2 Location Paths – 2.5 Abbreviated Syntax
  • @CiaPan : 我没有粘贴整个 xml 文档,这是特定部分
  • 那么,发布不是格式良好的 XML 的源代码子集是没有意义的。我们不知道应该在哪里关闭未关闭的开始标签。
  • @MichaelKay : 在我的问题中更新了我的 xml

标签: java dom xpath xml-parsing


【解决方案1】:

一旦您选择了 document-id 节点,// 运算符就会选择它的所有后代,
然后text() 将它们中的每一个转换为一个字符串。如果您只想处理一些后代节点,只需列出它们(构建一个显式的子元素序列)。
您还可以摆脱昂贵的(在这里是多余的!)// 运营商。
尝试将查询替换为
"//family-member/publication-reference/document-id[@document-id-type=\"docdb\"]/(国家,日期)/text()"

【讨论】:

  • 哎呀,你是对的,这似乎是 XQuery 语法,而不是纯粹的 XPath!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
相关资源
最近更新 更多