xpath:为每个子节点获取父节点的值

马克西米利安·塔尔塔尼亚

鉴于此XML:

<child id="1"  name="alpha" >Some Text</child
<child id="2"  name="beta" > 
  <grandchild id="2.1"></grandchild> 
  <grandchild id="2.2"></grandchild> 
</child> 
<child id="3"  name="gamma"  mark="yes" > 
  <grandchild id="3.1"  name="gamma-alpha"> </grandchild> 
  <grandchild id="3.2"  name="gamma-beta" ></grandchild> 
</child>

有4个孙子节点,我想获取它们的所有父节点(在我的示例数据中恰好是“子”节点)id值。我自己的微弱尝试:

// grandchild / parent :: child / @ id

返回:

text{"2"}, 
text{"3"}

只是,但是

text{"2"},
text{"2"}, 
text{"3"},
text{"3"}

是我想看到的。

马丁·洪恩

您将需要使用宿主语言来遍历grandchild元素并访问parent::child/@id每个元素,或者您需要移至XPath 2.0(https://www.w3.org/TR/xpath20/#id-for-expressions)或更高版本,使用for $gc in //grandchild return $gc/parent::child/@id或升级到XPath 3.0(https://www.w3.org/TR/xpath-30/#id-map-operator)或更高版本并使用//grandchild!parent::child/@id使用XPath /exp,选择节点的路径中的任何步骤都可以消除重复项,因此您不能使用单个表达式来/id您拥有的两个元素返回四个属性。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章