smolesen
smolesen

Reputation: 1333

XPath substring-after

Given the following XML:

<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20">
    <shipTo country="US">
        <name>Alice Smith</name>
        <street>123 Maple Street</street>
        <city>Mill Valley</city>
        <state>CA</state>
        <zip>90952</zip>
    </shipTo>
    <billTo country="US">
        <name>Robert Smith</name>
        <street>8 Oak Avenue</street>
        <city>Old Town</city>
        <state>PA</state>
        <zip>95819</zip>
    </billTo>
    <comment>Hurry, my lawn is going wild!</comment>
    <items>
        <item partNum="872-AA">
            <productName>Lawnmower</productName>
            <quantity>1</quantity>
            <USPrice>148.95</USPrice>
            <comment>Confirm this is electric</comment>
        </item>
        <item partNum="926-AA">
            <productName>Baby Monitor</productName>
            <quantity>1</quantity>
            <USPrice>39.98</USPrice>
            <shipDate>1999-05-21</shipDate>
        </item>
    </items>
</purchaseOrder>

how do I select the '98' from the USPrice in the 2nd item. I've tried:

purchaseOrder/items/item[USPrice[text()='39.98']]/USPrice/substring-after(.,'.')

but it keep giving me the error 'has an invalid token'

if I try:

purchaseOrder/items/item[USPrice[text()='39.98']]/USPrice/text()[substring-after(.,'.')]

or

purchaseOrder/items/item[USPrice[text()='39.98']]/USPrice[substring-after(text(),'.')]

I get '39.98' which is wrong too.

I'm testing using the site here:

http://www.xmlme.com/XpathTool.aspx

Upvotes: 2

Views: 1475

Answers (3)

Pekka
Pekka

Reputation: 3654

Save the value of /purchaseOrder/items/item[2]/USPrice into a variable (say Price), and then use $Price - floor($Price) to calculate the factional portion of the price.

Using substring-after() will fail to return anything if the value is an even number of dollars, which could cause the remainder of the transform to return incorrect results.

Upvotes: 0

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243579

The XPath expression you are after is:

substring-after(/purchaseOrder/items/item[2]/USPrice, '.')

You can evaluate this XPath expression directly in C# code (without XSLT) using XPathNavigator.Evaluate()

Upvotes: 1

Treemonkey
Treemonkey

Reputation: 2163

strictly speaking you cannot do this using xpath 1.0

using XSLT the following would work, but i don't think this is what you require

<xsl:value-of select="substring-after(purchaseOrder/items/item[2]/USPrice,'.')"/>

please refer to this similar question for more information

How to apply the XPath function 'substring-after'

Upvotes: 3

Related Questions