Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting child nodes using XPATH

Tags:

xpath

I have following XML

<orderList>
    <orderInfo orderId="xyz" returnCode="Pending" />
    <orderInfo orderId="yzz" returnCode="Shipped">
        <orderDetail shipped-date="xxxx-xx-xx xx:xx:xx">
            <order>
               ....
            </order>
        </orderDetail>
    </orderInfo>
</orderList>

I want to count # of order under each orderDetail item ...

I tried this link (XPath to count the child nodes based on complex filter) but it didn't help

I came up with this path

count(//orderList/orderInfo/orderDetail[count(order)])

like image 720
Em Ae Avatar asked Jun 10 '14 15:06

Em Ae


1 Answers

If you want to count all order elements in the orderList/orderInfo/orderDetail nodes (ignoring their current context), then you could use:

count(//orderList/orderInfo/orderDetail/order)

If you want to count the number of orders for a specific orderDetail, then you should use a predicate to select which orderDetail you want:

count(//orderList/orderInfo/orderDetail[@shipped-date="xxxx-xx-xx xx:xx:xx"]/order)

Unless you are using XPath 2.0 or a greater version, you won't be able to return a collection of results with a single expression. But you can select all orderDetail elements (//orderList/orderInfo/orderDetail), iterate through them and count the order elements in the current context, or set the predicate value as a variable to select a specific orderDetail.

like image 71
helderdarocha Avatar answered Nov 16 '22 22:11

helderdarocha