Kalmar
Kalmar

Reputation: 65

XML XPath find all nodes with attribute and his parent

I want to write XPath query that will return from this xml

<?xml version="1.0" encoding="UTF-8"?>

<contents> 
  <content type="menu_0" nested="yes"> 
    <content type="name" lang="pol"><![CDATA[PIES]]></content>  
    <content type="menu_1" nested="yes"> 
      <content type="name" lang="pol"><![CDATA[Thing1]]></content>  
      <content type="name" lang="pol"><![CDATA[Thing2]]></content>  
      <content type="name" lang="pol"><![CDATA[Thing3]]></content> 
    </content> 
  </content> 
</contents>

something like this

PIES\Thing1
PIES\Thing2
PIES\Thing3

Can someone help?:)

Upvotes: 0

Views: 111

Answers (1)

SomeDude
SomeDude

Reputation: 14238

Using XPath 1.0 you cannot get all the nodes as desired with PIES\ concatenated to Thing*, you need to use three xpath expressions like below :

concat( //content[@type='menu_0']/content[@type='name']/text(), '\',  //content[@type='menu_0']/content[@type='menu_1']/content[1]/text())

concat( //content[@type='menu_0']/content[@type='name']/text(), '\',  //content[@type='menu_0']/content[@type='menu_1']/content[2]/text())

concat( //content[@type='menu_0']/content[@type='name']/text(), '\',  //content[@type='menu_0']/content[@type='menu_1']/content[3]/text())

With XPath 2.0, you could use a for-loop to return the list in one xpath expression as below:

for $thing in //content[@type='menu_0']/content[@type='menu_1']/content/text()
   return concat( //content[@type='menu_0']/content[@type='name']/text(), '\',  $thing )

Upvotes: 1

Related Questions