使用 xpath 查询和选择分支 [英] Query and select over branches using xpath

查看:28
本文介绍了使用 xpath 查询和选择分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个 XML 文档,其中包含 ZIP=2222 和 NAME=Meier 的所有条目的 NAME、FIRSTNAME 和 STR.

I want to get an XML document containing NAME, FIRSTNAME and STR of all entries where ZIP=2222 and the NAME=Meier.

输入是:

<ROOT> 
<REC>
  <CONTACT>
    <NAME>Schmidt</NAME>
    <FIRSTNAME>Hans</FIRSTNAME>
  </CONTACT>
  <CONTACT>
    <NAME>Schmidt</NAME>
    <FIRSTNAME>Kurt</FIRSTNAME>
  </CONTACT>
  <LOC>
    <ZIP>1111</ZIP>
    <STR>Mainroud</STR>
  </LOC>
</REC>
<REC>
  <CONTACT>
    <NAME>Meier</NAME>
    <FIRSTNAME>Elise</FIRSTNAME>
  </CONTACT>
  <LOC>
    <ZIP>2222</ZIP>
    <STR>Castlestreet</STR>
  </LOC>
</REC>
</ROOT>

所需的输出:

 <OUT>
    <NAME>Meier</NAME>
    <FIRSTNAME>Elise</FIRSTNAME>
    <STR>Castlestreet</STR>
 </OUT>

我试过了:

/ROOT/REC[.//ZIP="2222" and .//NAME/text()="Meier"]

返回匹配的 REC 元素,但如何格式化输出.如果可能,我只想使用 Xpath,而不是 Xquery?

Which returns the matching REC elements, but how can I format the output. I would like to use Xpath only, not Xquery if possible?

推荐答案

你能做的最好的事情就是指定你想要在你的输出中包含哪些节点,但那些不会包含在 节点,因为原始 XML 中没有.如果您需要特定节点的列表,则必须将 XPath 更改为如下所示:

The best thing you can do is specify which nodes you want to have in your output, but those will not be included into an <OUT> node, because there's none in original XML. In case you want a list of specific nodes you'll have to alter your XPath to something like this:

/ROOT/REC[.//ZIP="2222" and .//NAME/text()="Meier"]//(NAME|ZIP|STR)

这会给你以下结果:

<NAME>Meier</NAME>
<ZIP>2222</ZIP>
<STR>Castlestreet</STR>

结果是节点集合,而不是具有子节点的单个节点,您必须遍历集合.不完全是您所要求的,但关闭了我仅使用 XPath 所能想到的.

The result is nodes collection, not single node with child nodes, you'll have to iterate over the collection. Not exactly what you were asking for, but closes what I could come up with using only XPath.

这篇关于使用 xpath 查询和选择分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆