Home > Mobile >  Combining 2 XPath Queries [@attribute and last()]
Combining 2 XPath Queries [@attribute and last()]

Time:03-19

I have an XML document that has multiple instances of 'User Area' node as below:

        <UserArea>
            <Property>
                <NameValue name="ShipDate">2022-01-27</NameValue>
            </Property>
            <Property>
                <NameValue name="ShipTime">12:07</NameValue>
            </Property>
            <Property>
                <NameValue name="CartonID">00000100270000031369</NameValue>
            </Property>
            <Property>
                <NameValue name="ShippingID">9</NameValue>
            </Property>
            <Property>
                <NameValue name="WeightType">Actual</NameValue>
            </Property>
            <Property>
                <NameValue name="FreeFreight">yes</NameValue>
            </Property>
            <Property>
                <NameValue name="BOLNo">128018300</NameValue>
            </Property>
        </UserArea>

I am trying to find the very last value for @name="BOLNo".

When I use this XPath Query it returns all 10 of the values: /UserArea/Property/NameValue[@name="BOLNo"]

How can I use last() with this XPath to get only the last instance of this value?

Thanks so much in advance!

CodePudding user response:

Wrapping in Parens did the trick!

(/UserArea/Property/NameValue[@name="BOLNo"])[last()]

CodePudding user response:

If every UserArea has exactly one BOLNo you also could use:

//UserArea[last()]/Property/NameValue[@name='BOLNo']

If not every UserArea has a BOLNo you could also use:

//UserArea[Property/NameValue/@name='BOLNo'][last()]/Property/NameValue[@name='BOLNo']

And as a easy alternative you could also use:

(//NameValue[@name="BOLNo"])[last()]
  • Related