September 13, 2010

XPath Based Mapping - Geocode Example

In a previous post I introduced MOXy's XPath based mapping JAXB extension.  In this post I'll use Google Maps Geocoding API V2 to demonstrate how powerful this extension is.

Input XML Document

The following is the sample document used on the Google Maps Geocoding API V2 page.

<?xml version="1.0" encoding="UTF-8" ?>
<kml xmlns="">
        <name>1600 Amphitheatre Parkway, Mountain View, CA</name>
        <Placemark id="p1">
            <address>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA
            <AddressDetails Accuracy="8" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
                            <SubAdministrativeAreaName>Santa Clara</SubAdministrativeAreaName>
                                <LocalityName>Mountain View</LocalityName>
                                    <ThoroughfareName>1600 Amphitheatre Pkwy</ThoroughfareName>
                <LatLonBox north="37.4251799" south="37.4188847" east="-122.0813633" west="-122.0876585" />

Java Model - Address

In this example we will map a portion of the geocode data to a typical address object.  Here we will make use of MOXy's @XmlPath annotation.  The get/set methods have been omitted to save space. 

The namespace qualification of the XPath corresponds to the configuration in the @javax.xml.bind.annotation.XmlSchema annotation on the package-info class.  XPath fragments with out a prefix correspond to the default namespace (""), and fragments prefixed with "ns" correspond to the namespace "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0".

package blog.geocode;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlType(propOrder={"country", "state", "city", "street", "postalCode"})
public class Address {

    private String street;

    private String city;

    private String state;

    private String country;

    private String postalCode;


Java Model - package-info

We will supply a package-info class to specify the namespace qualication, and field access.

                @XmlNs(prefix="ns", namespaceURI="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0")
package blog.geocode;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

Java Model -

In order to specify that we are using the MOXy JAXB implementation we need to put a file called in with our Address class with the following entry: 


Demo Code

The following code can be used to demonstrate our mapping.  In the URL creation be sure to replace the string "YOUR_KEY_HERE" with your own API key.  If you do not have one, you can create one here.

package blog.geocode;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Address.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        URL xmlURL = new URL(",+Mountain+View,+CA&output=xml&sensor=false&key=YOUR_KEY_HERE");
        InputStream xml = xmlURL.openStream();
        Address address = (Address) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(address, System.out);



The following is the output from running our Demo class.  Note that only the portion of the document that we mapped will be output to XML.

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="" xmlns:ns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
                                <ns:LocalityName>Mountain View</ns:LocalityName>
                                    <ns:ThoroughfareName>1600 Amphitheatre Pkwy</ns:ThoroughfareName>

Further Reading:

If you enjoyed this post you may also be interested in:


  1. Blaise,
    Is it possible to annotate the fields (assume default namesapce)

    @XmlPath("//Point/coordinates") instead of

    Using the "any-level descendant" syntax doesn't work as in I get values as null. Thanks for your help and excellent tutorial on moxy impl.

  2. Hi JT,

    The reason we don't allow the "any-level" concept frpm XPath is that we require that information when marshalling to XML.

    Are you interested in this type of functionality for unmarshal only use cases?


  3. Hi,

    I'd be definitely interested in unmarshal-only use-cases.


  4. Hi Zdenek,

    Sorry for the delay in responding. I haven't had a chanve to post an example yet, but if you want to try somethings out yourself just include your XPath in the @XmlPath annotation and make the following magic call after you create your JAXBContext:
      JAXBHelper.getJAXBContext(jc).getXMLContext().getSession(0).getDatasourceLogin().setDatasourcePlatform(new DOMPlatform());


  5. This is really exciting.
    Unfourtnately I get exception:
    javax.servlet.ServletException: java.lang.NoSuchMethodError: org.eclipse.persistence.oxm.NamespaceResolver.hasPrefixesToNamespaces()Z

    1. Which environment are you running in? It appears as though you may be using the EclipseLink OSGi bundles, and using a new MOXy bundle and an older core bundle.


  6. This tutorial is great, However when I try to unmarshal a json string to java beans using the code mentioned above I get the following error:

    Exception in thread "main" javax.xml.bind.PropertyException: name: value: application/json
    at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(Unknown Source)
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.setProperty(
    at sample.TestJSON.main(

    I have downloaded latest eclipse link jars and have created a file as well.Can you please help me resolve this problem,

    1. Hi Anusha,

      I have another post covering the JSON aspect of the Geocode API that you may be interested in:
      - Binding to JSON & XML - Geocode Example

      For that post I have the complete source code available on GitHub:


    2. Is this propertyException specific to geocoding? I get it too

  7. Excellent Post..Can you please help me configure EclipseLink MoxY in Spring?


Note: Only a member of this blog may post a comment.