Simplifying Maps for Optional Elements

Because the rules behind XML maps allow for multiple overlapping assignments, you can simplify your maps when handling alternate or optional elements. For example, consider the following XML snippet, which contains common <name> and <address> elements, but different elements for the postal code value.

    <address>
        <name>Don Rumsfeld</name>
        <usZipCode>52332</usZipCode>
    </address>
    <address>
        <name>Tony Blair</name>
        <britishPostalCode>4F3-G5H</britishPostalCode>
    </address>

When you expect to receive a message that will contain one or the other, you can simplify your XML map as follows:

    /*
      * @jws:parameter-xml xml-map::
      * <getFullAddress>
      * <address>
      *     <name>{name}</name>
      *     <usZipCode>{postalCode}</usZipCode>
      *     <britishPostalCode>{postalCode}</britishPostalCode>
      * </address>
      * </getFullAddress>
      * ::
      */
    public int getFullAddress(String name, String postalCode)
    {...}

In this example, either the value for <usZipCode> or for <britishPostalCode> will be mapped to the postalCode parameter, depending on which the message contained.

# Assignment Order for Alternate Mapping

Note that if both the <usZipCode> and <britishPostalCode> elements included content in the same message, the last one in the order would overwrite the previous (from the preceding example, <britishPostalCode> would overwrite <usZipCode>. This is just what would occur if you assigned two values to the same variable in Java code: the first would be displaced by the second.

Related Topics

Matching XML Shapes

Making Simple Substitutions Using Curly Braces