I have a very basic XML and wanted to write an Xpath query to get a value. Here is XML:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<address>
<type>STD</type>
<key>1234</key>
</address>
<address>
<type>BA</type>
<key>1234</key>
</address>
<phone>
<type>TEL</type>
<key>1234</key>
<telephonenum>7</num>
</phone>
<phone>
<type>TEL</type>
<key>1234</key>
<telephonenum>8</num>
</phone>
<phone>
<type>TEL</type>
<key>1234</key>
<telephonenum>9</num>
</phone>
</person>
Here are the conditions I have:
If (/person/address[type = "STD"]/addresskey = and /person/address[type = "BA"/addresskey )
then I should get the /person/phone[2]/telephonenum
. If this second telephone number doesn't exist then it should get the first telephone number.
I guess that by
addresskey
you mean justkey
(there is noaddresskey
element in the provided XML).Also, the XML is not wellformed and I had to correct ie.
Now let us address the stated requirements:
First:
Translates to this:
Then:
Modifies the above expression to this:
Finally:
the complete expression becomes:
XSLT - based verification:
when this transformation is applied on the provided (and corrected) XML:
the wanted node is selected and output:
II. XPath 2.0 expression: