Question

Given:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<report Id="0" >
<property name="comments">comment</property>
<property name="test">sdcs</property>
<property name="test">csd</property>
<property name="eventHandlerClass">sdcs</property>
</report>
<report  Id="1">
<property name="comments">comment</property>
<property name="test">dcs</property>
<property name="test">gds</property>
<property name="test">jds</property>
<property name="eventHandlerClass">sdcs</property>
</report>
</root>

Expected output:

Id=0, test=sdcs
Id=0, test=csd
Id=1, test=dcs
Id=1, test=gds
Id=1, test=jds

Only looking for a plain Xpath 1.0 to achieve this. Tried varioud functions and predicates but fail to get an output like above. Essentially, after reading I should be able to tell which "test" belongs to which report Id.

Tried:

/root/report/@Id | /root/report/property[@name="test"] -- But gives result in separate lines

/root/report/ ( @Id | property[@name="test"]) -- But gives result in separate lines

concat( /root/report/@Id, /root/report/property[@name="test"]) -- Gives error (think Concat works on single line result)

string-join(/root/report/@Id | /root/report/property[@name="test"] , ',') -- All comes as a single line, even two report Ids.

Was it helpful?

Solution

You can use for for that to keep the id in a variable:

for $report in /root/report 
return for $property in $report/property[@name="test"]
return concat("Id=", $report/@Id, ", ", $property/@name, "=", $property)

Or shorter:

for $report in /root/report return
$report/property[@name="test"]/
concat("Id=", $report/@Id, ", ", @name, "=", .)

OTHER TIPS

you can do this quite elegantly with by making the primary "iteration elements" be the deepest child - in this example the XML root-element is TABLE. See how we "iterate" over the deeper child called COLUMN. We take the COLUMN's @name (second), and add the parent's-parent's @name attribute

/TABLE/COLUMNS/COLUMN/concat(../../@name, ' : ', @name)

This eliminates the need to use a variable for the parent's @name

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top