Handling Repeating XML Values with <xm:multiple>

An XML message may contain elements that occur multiple times within the message's structure. In the following example, the <part> element and its children repeat three times to make up a single order.

    <order>
        <part>
            <partID>19573</partID>
            <partQuantity>4</partQuantity>
        </part>
        <part>
            <partID>28912</partID>
            <partQuantity>1</partQuantity>
        </part>
        <part>
            <partID>39485</partID>
            <partQuantity>57</partQuantity>
        </part>
    </order>

To handle all of the repeating elements — perhaps choosing from among them iteratively — you can capture the values for repeating elements in a Java data structure such as an array. You can use the <xm:multiple> attribute to capture the values for the repeating elements in a Java data structure, then iterate through the structure in your code.

The following example is designed to operate on an incoming XML message like the preceding example. In this example, the <xm:multiple> attribute specifies that the contents of the <partID> and <numberOfItems> elements should be added as members of the serialNumber and quantity arrays.

    /**
     * @jws:operation
     * @jws:parameter-xml xml-map::
     * <placeOrder>
     * <order>
     *      <part xm:multiple="String serial in serialNumber, int quant in quantity">
     *         <partID>{serialNumber}</partID>
     *         <numberOfItems>{quantity}</numberOfItems>
     *      </part>
     * </order>
     * </placeOrder>
     * ::
     */
    public void placeOrder(String[] serialNumber, int[] quantity)
    {
          for (int i = 0; i < serialNumber.length; i++)
          {
            System.out.println("Ordered " + quantity[i] + " of part " + serialNumber[i]);
          }
    }

Note that this also works in reverse. For example, if this were a callback, and the parameters were being mapped to an outgoing (rather than incoming) message, the map above would result in XML like the example preceding it.

# Mapping Repeating XML Values to a Java Return Values

This technique is also useful when the repeating values correspond to a Java return value, rather than a parameter. Note that in the following example, the word return is used to indicate that the return value is being mapped.

    /**
     * @jws:operation
     * @jws:return-xml xml-map::
     * <returnPartNames>
     *     <partName xm:multiple="String i in return">{i}</partName>
     * </returnPartNames>
     * ::
     */
    public String[] getPartNames(String[] serialNumber)
    {...}

For reference information on using the <xm:multiple> attribute, see <xm:multiple> Attribute.

Related Topics

Matching XML Shapes

<xm:multiple> Attribute

<xm:bind> Attribute