如何通过引用的属性查找元素?

时间:2015-12-03 11:59:42

标签: xpath reference

我有一个关于将XPath表达式作为属性值传递的快速问题。 所以我有以下文件:

<?xml version="1.0"?>

<personnel>
<person id="EMP01" >
  <name><family>Lee</family><given>Ho</given></name>
  <email>lee.ho@foo.com</email>
  <salary>100000</salary>
  <links>
    <subordinate>EMP02</subordinate>
    <subordinate>EMP03</subordinate>
  </links>
</person>

<person id="EMP02">
  <name><family>Chan</family><given>Tai Man</given></name>
  <email>chan.tai.man@foo.com</email>
  <salary>20000</salary>
  <links>
    <manager>EMP01</manager>
    <subordinate>EMP04</subordinate>
    <subordinate>EMP05</subordinate>
  </links>
</person>

<person id="EMP03">
  <name><family>Cheung</family><given>Siu Fan</given></name>
  <email>cheung.siu.fan@foo.com</email>
  <salary>20200</salary>
  <links>
    <manager>EMP01</manager>
    <subordinate>EMP07</subordinate>
  </links>
</person>

<person id="EMP04">
  <name><family>Ng</family><given>Ho</given></name>
  <email>ng.ho@foo.com</email>
  <salary>11000</salary>
  <links>
    <manager>EMP02</manager>
  </links>
</person>

<person id="EMP05">
  <name><family>Chow</family><given>Sing Sing</given></name>
  <email>chow.sing.sing@foo.com</email>
  <salary>20050</salary>
  <links>
    <manager>EMP02</manager>
    <subordinate>EMP06</subordinate>
  </links>
</person>

<person id="EMP06">
  <name><family>Law</family><given>Lai</given></name>
  <email>law.lai@foo.com</email>
  <salary>5050</salary>
  <links>
    <manager>EMP05</manager>
  </links>
</person>

<person id="EMP07">
  <name><family>Chan</family><given>Siu Ming</given></name>
  <email>chan.siu.ming@foo.com</email>
  <salary>5000</salary>
  <links>
    <manager>EMP03</manager>
  </links>
</person>

我需要一个XPath表达式来获取姓名为Law的家庭经理的人员节点,所以在这种情况下,周先生。但是如何在没有明确使用名称Chow的情况下在XPath中获取它?

我的尝试是:

personnel/person[@id="personnel/person/name/family='Law'"] 

但它并没有真正起作用......我可以将XPath作为这样的属性的值传递,或者我该如何做?

2 个答案:

答案 0 :(得分:1)

如果希望将字符串作为XPath表达式而不是文字字符串读取,请不要使用引号。尝试这样的事情:

/personnel/person[@id=/personnel/person[name/family='Law']/links/manager]/name/family

<强> xpathtester demo

输出

<family>Chow</family>

答案 1 :(得分:0)

你可以这样做:

personnel/person[name/family = 'Law']

这样就可以获得整个人员节点。

http://www.xpathtester.com/xpath/76e78418ba5de7779394705dba0585f3