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

75 Views Asked by At

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!

2

There are 2 best solutions below

4
On

If every UserArea has exactly one BOLNo and all UserArea's belong to the same parent, you also could use:

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

If not every UserArea has a BOLNo and all UserArea's belong to the same parent you could also use:

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

If all UserArea's do not belong to the same parent, you could also use this simple XPath (is slower at huge xml-content):

(//NameValue[@name="BOLNo"])[last()]
5
On

Wrapping in Parens did the trick!

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