Can XPath do a foreign key lookup across two subtrees of an XML?

Deadly 提交于 2019-11-28 01:19:24

问题


Say I have the following XML...

<root>
  <base>
    <tent key="1" color="red"/>
    <tent key="2" color="yellow"/>
    <tent key="3" color="blue"/>
  </base>
  <bucket>
    <tent key="1"/>
    <tent key="3"/>
  </bucket>
</root>

...what would the XPath be that returns that the "bucket" contains "red" and "blue"?


回答1:


If you're using XSLT, I'd recommend setting up a key:

<xsl:key name="tents" match="base/tent" use="@key" />

You can then get the <tent> within <base> with a particular key using

key('tents', $id)

Then you can do

key('tents', /root/bucket/tent/@key)/@color

or, if $bucket is a particular <bucket> element,

key('tents', $bucket/tent/@key)/@color



回答2:


I think this will work:

/root/base/tent[/root/bucket/tent/@key = @key ]/@color



回答3:


It's not pretty. As with any lookup, you need to use current():

/root/bucket[/root/base/tent[@key = current()/tent/@key]/@color = 'blue' or /root/base/tent[@key = current()/tent/@key]/@color = 'red']




回答4:


JeniT has the appropriate response / code listed here. You need to create the key before you walk the XML Document, then perform matches against that key.



来源:https://stackoverflow.com/questions/142010/can-xpath-do-a-foreign-key-lookup-across-two-subtrees-of-an-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!