Can XPath search for a foreign key through two XML subtrees?

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 will be the XPath that returns that the "bucket" contains "red" and "blue"?

+4
source share
4 answers

If you are using XSLT, I would recommend setting up the key:

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

Then you can get the <tent> inside the <base> with a specific key using

 key('tents', $id) 

Then you can do

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

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

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

I think this will work:

 /root/base/tent[/root/bucket/tent/@key = @key ]/@color 
+2
source

It's not beautiful. As with any search, 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']

+1
source

JeniT has the corresponding answer / code indicated here. You need to create a key before going through an XML document, and then match that key.

0
source

Source: https://habr.com/ru/post/1277235/


All Articles