Fork me on GitHub

Tutorial 18

E18 Using XMLBeam without a projection interface to resolve a postal code

This example demonstrates using XMLBeam without a projection interface.

  • Using direct evaluation API
  • Retrieve data from multiple address components without iterating manually through elements

XML Data

The postal code is stored in one of many address_component elements. With data binding you would need to iterate over all of these elements to find the one containing the postal code.

<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>route</type>
  <formatted_address>Infinite Loop, Cupertino, CA 95014, USA</formatted_address>
  <address_component>
   <long_name>Infinite Loop</long_name>
   <short_name>Infinite Loop</short_name>
   <type>route</type>
  </address_component>
  <address_component>
   <long_name>Cupertino</long_name>
   <short_name>Cupertino</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Santa Clara County</long_name>
   <short_name>Santa Clara County</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>California</long_name>
   <short_name>CA</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>United States</long_name>
   <short_name>US</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>95014</long_name>
   <short_name>95014</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>37.3319426</lat>
    <lng>-122.0307481</lng>
   </location>
   <location_type>GEOMETRIC_CENTER</location_type>
   <viewport>
    <southwest>
     <lat>37.3305175</lat>
     <lng>-122.0321699</lng>
    </southwest>
    <northeast>
     <lat>37.3334980</lat>
     <lng>-122.0285561</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>37.3305175</lat>
     <lng>-122.0321699</lng>
    </southwest>
    <northeast>
     <lat>37.3334980</lat>
     <lng>-122.0285561</lng>
    </northeast>
   </bounds>
  </geometry>
 </result>
</GeocodeResponse>

Example Code

You only need just one line of code to read the postal code. You do not need even a projection interface in this case.

public void postalCodeRetrieval() {
    String searchURL="http://maps.google.com/maps/api/geocode/xml?address=Infinite%20Loop,%20Cupertino,%20CA%2095014,%20USA%22";
    String pathToElement="/GeocodeResponse/result/address_component[type='postal_code']/long_name";
 
    long postalCode = new XBProjector().io().url(searchURL).evalXPath(pathToElement).as(Long.TYPE);
 
    assertEquals(95014L,postalCode);
}