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

时间:2017-01-08 11:16:20

标签: xml 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个孙子节点,并且我想获得他们所有的父母(恰好是我的示例数据中的&#34;孩子&#34;节点)id值。我自己的微弱尝试:

//孙子/父::子/ @ ID

返回:

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

,但

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

是我想看到的。

1 个答案:

答案 0 :(得分:4)

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