Filtering Multiple Children With Predicates

When using the . or .. operator returns multiple children, you can use the .() (predicate) operator to further filter your results based on specific criteria. The .() operator works in a manner similar to the XPath [ ] operator, which constitutes what is known as a "predicate" of the path.

The following function examples, based on this xmlEmployees variable, return information about an employee based on a filtering value.

    /* Declare an XML variable with a literal XML value. */
    var xmlEmployees = <employees>
        <employee id="111111111">
            <firstname>John</firstname>
            <lastname>Walton</lastname>
            <age>25</age>
        </employee>
        <employee id="222222222">
            <firstname>Sue</firstname>
            <lastname>Day</lastname>
            <age>32</age>
        </employee>
    </employees>;
    /*
     * Return the <employee> element for the employee whose last name

     * is "Day".
     * This code returns an XMLList type containing:
     *    <employee id="222222222">
     *        <firstname>Sue</firstname>
     *        <lastname>Day</lastname>
     *        <age>32</age>
     *    </employee>
    /*
        var empDay = xmlEmployees..employee.(lastname == "Day");

    /*
     * Return the age of the employee whose id is "111111111".
     * This code returns an XMLList type containing "25".
     */
    var empAge = xmlEmployees..employee.(thisXML.@id == "111111111").age;

When elements have names that conflict with ECMAScript keywords or function names, you can use the following syntax for filtering instead. Note that there are two different workarounds — one is for use with ECMAScript keywords and the other is for use with function names. Both require using the thisXML property.

    /*
     * Return all of the <if> elements.
     * This avoids a conflict with the "if" ECMAScript keyword.
     */
    var ifs = xmlData.product_description.(thisXML["if"] == "43-0t654-09");
    /*
     * Return the first <parent> element.
     * This avoids a conflict with the parent function.
     */
    var firstParent = xmlFamilies.kid.(thisXML.::parent == "Johnson");

Related Topics

Accessing Element Descendants with the .. Operator