I have this XML:
<property id="1011">
<leasehold>No</leasehold>
<freehold>Yes</freehold>
<propertyTypes>
<propertyType>RESIDENTIAL</propertyType>
</propertyTypes>
</property>
and I want to create an xpath statement that is same as the following nested if-else pseudocode block.
if( propertyTypes/propertyType == 'RESIDENTIAL') {
if( leasehold == 'Yes' ){
return 'Rent'
} else
return 'Buy'
}
} else {
if( leasehold == 'Yes' ){
return 'Leasehold'
} else
return 'Freehold'
}
}
I've seen something about Becker's method but I couldn't really follow it. XPath isn't my strong point really.
Spent all day today, but works for me this is for Xpath 1.0:
Try this
I. In XPath 2.0 one simply translates this to:
XSLT 2.0 - based verification:
When this transformation is applied on the provided XML document:
the XPath expression is evaluated and the result of this evaluation is copied to the output:
II. XPath 1.0 solution
In XPath 1.0 there isn't an
if
operator.A conditional statement can still be implemented with a single XPath 1.0 expression, but this is more tricky and the expression may not be too readable and understandable.
Here is a generic way (first proposed by Jeni Tennison) to produce
$stringA
when a condition$cond
istrue()
and otherwise produce$stringB
:One of the main achivements of this formula is that it works for strings of any length and no lengths need to be specified.
Explanation:
Here we use the fact that by definition:
and
and that
So, if
$cond
isfalse
, the first argument ofconcat()
above is:and this is the empty string, because
$stringA
has a finite length.On the other side, if
$cond
istrue()
then the first argument ofconcat()
above is:that is just
$stringA
.So, depending on the value of
$cond
only one of the two arguments ofconcat()
above is a nonempty string (respectively$stringA
or$stringB
).Applying this generic formula to the specific question, we can translate the first half of the big conditional expression into:
This should give you an idea how to translate the whole conditional expression into a single XPath 1.0 expression.
XSLT 1.0 - based verification:
When this transformation is applied on the provided XML document (above), the XPath expression is evaluated and the result of this evaluation is copied to the output:
Do note:
If you decide to replace the specific strings with other strings that have different lengths than the original, you simply replace these strings in the above XPath 1.0 expression and you don't have to worry about specifying any lengths.
Becker's method for your data is the following: