从已知子项的值中获取父属性

时间:2015-01-05 21:51:10

标签: xml xpath

尝试根据一个或多个孩子的价值选择一个元素的attriibute,无论多深。

想到以下但没有工作,感谢任何帮助,谢谢!

"//*[node()[contains(text(), 'FirstInfo')] and node()[contains(text(), 'SecondInfo')]/::parent]"

这是XML:

<root>
<a ID="GetThisText">
  <b>
   <c>FirstInfo</c>

   <d>SecondInfo</d>
</b>
</a>
</root>

2 个答案:

答案 0 :(得分:1)

使用以下路径表达式

//a[descendant::c = 'FirstInfo' and descendant::d = 'SecondInfo']/@ID

转换为

//a                                  Find all elements `a` no matter where in the XML
                                     tree
[descendant::c = 'FirstInfo'         But only return them if they have a descendant
                                     element 'c' with the value "FirstInfo"
and descendant::d = 'SecondInfo']    and a descendant element "d" with the value
                                     "SecondInfo"
/@ID                                 of those elements `a` return the element `ID`.

并导致

ID="GetThisText"

答案 1 :(得分:0)

试试这个:

'//*[contains(., "FirstInfo")][contains(., "SecondInfo")]/ancestor::*/@ID'

或更好:

'//*[c="FirstInfo" and d="SecondInfo"]/ancestor::a/@ID'