counting child nodes using XPATH

21,835

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.

Share:
21,835
Em Ae
Author by

Em Ae

Updated on June 11, 2020

Comments

  • Em Ae
    Em Ae about 4 years

    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)])