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 just key
(there is no addresskey
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:
I should get the /person/phone[2]/telephonenum
.
Translates to this:
/*/phone[2]
Then:
If this second
telephone number doesn't exist then it should get the first telephone
number.
Modifies the above expression to this:
/*/phone[not(position() >2)][last()]
Finally:
If (/person/address[type = "STD"]/addresskey = and /person/address[type = "BA"/addresskey )
the complete expression becomes:
/*/phone[not(position() >2)][last()]
[/*/address[type = 'STD']/key
=
/*/address[type = 'BA']/key
]
XSLT - based verification:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select=
"/*/phone[not(position() >2)][last()]
[/*/address[type = 'STD']/key
=
/*/address[type = 'BA']/key
]
"/>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided (and corrected) XML:
<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</telephonenum>
</phone>
<phone>
<type>TEL</type>
<key>1234</key>
<telephonenum>8</telephonenum>
</phone>
<phone>
<type>TEL</type>
<key>1234</key>
<telephonenum>9</telephonenum>
</phone>
</person>
the wanted node is selected and output:
<phone>
<type>TEL</type>
<key>1234</key>
<telephonenum>8</telephonenum>
</phone>
II. XPath 2.0 expression:
for $check in
/*/address[type = 'STD']/key[1]
eq
/*/address[type = 'BA']/key[1],
$p1 in /*[$check]/phone[1],
$p2 in /*[$check]/phone[2]
return
($p2, $p1)[1]