Filtering By Namespace

When you expect XML messages with elements that use namespace prefixes, you can use a namespace variable to query the XML for elements contained in a specified namespace.

The syntax for the namespace declaration is as follows:

namespace namespaceVariable [as URIString]

The URIString value is the URI that uniquely identifies the namespace. By associating the variable with the namespace URI, you can then use the variable as you might use a namespace prefix. The syntax for using the namespace variable can be one of the following two variations. The first uses the . operator to separate elements in the hierarchy, which the second uses square brackets.

value = namespaceVariable::elementName1.namespaceVariable::elementName2;

value = ["namespace:elementName1"]["namespace:elementName2"];

The second variation is especially useful in cases where the element name conflicts with a script keyword (such as if or return). For more information about working around such conflicts, see A Few Things to Remember About XML Maps and Script.

In the following example, the "http://openuri.org/" namespace is associated with the myco variable.

    /* Declare an XML variable with a literal XML value. */
    var xmlEmps = <employeeData>
        <inc:employees xmlns:inc="http://openuri.org/">
            <inc:employee inc:id="111111111">
                <inc:name>John</inc:name>
                <inc:age>25</inc:age>
            </inc:employee>
        </inc:employees>
    </employeeData>;
    /* Declare a namespace variable to represent the namespace whose prefix is "inc". */
    namespace myco as "http://openuri.org/";
    /* Create a new variable to hold the <employee> node containing John.
     * Access the attributed elements by using the namespace variable in double-colons in place of the
     * prefix-colon combination used in the XML literal above.
     */
    var xmlName = xmlEmps.employeeData.myco::employees.myco::employee[0];

Note that accessing namespaced attributes works a little differently. Rather than using the .@ operator, as you might ordinarily when accessing attributes, you use the attribute method. In other words, instead of .@inc::id to access the inc:id attribute in the example, you would use the following:

    /* Create a new variable to hold the <employee> node containing John. */
    var xmlName = xmlEmps.employeeData.myco::employees.myco::employee.attribute("inc:id");

Related Topics

Accessing Element Children With the . Operator