XML Programming Information for Java

Building XML

 

Parsing XML

 

See UPS OnLine Tools Developer's Guide for tool specific Xpaths and options for formatting XML Requests.

Building XML

Before sending the request to the UPS OnLine Tools server, the request in the XML format has to be built. Each request is made up of two separate XML request documents-- the Access Request and the Service Request. These requests are concatenated and posted to the UPS web servers using a single HTTPS Post.

 

When validating the request XML documents, do not treat the two concatenated documents as a single XML document. XML parsers can not parse two concatenated documents. Validate each XML Request separately. UPS will separate the two documents and parse them individually. To ensure this occurs, verify that <?xml version="1.0"?> is at the top of each XML request document.

Building XML with IBM's API

IBM's XML4J is a 100% pure Java solution for building XML document and parse XML, and is available for both Java1 and Java2 VM. Refer to the API documentation from Alphaworks for more information on XML4J http://alphaworks.ibm.com.

 

Code Examples

The following code example shows how to create an XML document using XML4J:

 

protected Document createXMLDocument(String rootName) throws Exception

 

{

 

try{

 

//use the XML parser provided by IBM: XML4J

 

Document doc = new com.ibm.xml.parser.TXDocument();

 

Element root = doc.createElement(rootName);

 

doc.appendChild(root);

 

return doc;

 

}catch(Exception e)

 

{

 

System.out.println("Error in createXMLDocument" + e.getMessage());

 

throw new Exception ("Error in createXMLDocument" + e);

 

}

 

 

The following code shows how to add a node and its value to the XML document:

 

public static void addNode(Document doc, String strParentTag, String newTagName, String textString, String attrName, String attrValue

 

{

 

Element item = doc.createElement(newTagName); // this creates the new element tag

 

Node parentTag = doc.getDocumentElement(); // default parent to root

 

// we are getting a nodelist because it allows us to specify the parent element

 

// by its string name; that way, we don't have to pass Elements around

 

NodeList nl = doc.getDocumentElement().getElementsByTagName(strParentTag);

 

parentTag = nl.item(nl.getLength()-1);

 

try

 

{

 

if (textString != null)

 

{

 

// we support #RM, which means, 'do not add this node'

 

if(!textString.startsWith("#RM") && !textString.startsWith("#rm"))

 

{

 

item.appendChild(doc.createTextNode(textString));

 

parentTag.appendChild(item);

 

}

 

}

 

else

 

{

 

if(attrName != null && attrValue != null)

 

item.setAttribute(attrName, attrValue);

 

parentTag.appendChild(item);

 

}

 

}

 

catch (Exception e)

 

{

 

e.printStackTrace();

 

}

 

}

 

 

Calling the above two methods, AccessAdapter builds the AccessRequest XML document from an Access object as illustrated in the code example below:

 

Public Class AccessAdapter

 

{

 

public StringBuffer adaptFromObject(Access acc) throws Exception

 

{

 

StringBuffer xmlBuf = new StringBuffer();

 

try{

 

Document doc = createXMLDocument(XML_AccessRequest);

 

Element root = doc.getDocumentElement();

 

root.setAttribute("xml:lang", "en-US");

 

// build access info

 

addNode(doc, XML_AccessRequest, XML_AccessLicenseNumber, acc.getLicenseNumber(), null, null);

 

addNode(doc, XML_AccessRequest, XML_UserId, acc.getUserId(), null, null);

 

addNode(doc, XML_AccessRequest, XML_Password, acc.getPassword(), null, null);

 

 

 

// convert Document to StringBuffer

 

xmlBuf = docToBuffer(doc);

 

} catch (Exception e)

 

{

 

System.out.println("Error in adaptFromObject --> " + e.getMessage());

 

}

 

return xmlBuf;

 

}

 

}

 

Building XML with Sun's API

Sun Microsystems provides a Java API for XML Parsing (JAXP). JAXP enables loose coupling between a vendor implementation and a Java application using JAXP's API's. With JAXP, a system property can be used to specify the parser to use instead of importing a vendor�s parser class directly in the code. In this way, changing the parser implementation to be used requires only a change to the system property specifying the parser class to JAXP without changing the application codes. For more information on JAXP, refer to http://java.sun.com/xml/.

 

Code Example

The following sample code shows how to create XML document with JAXP API:

 

// This method creates the XML document and its root node

 

protected Document createXMLDocument(String rootName) throws Exception

 

{

 

try{

 

//use package javax.xml.parsers

 

javax.xml.parsers.DocumentBuilderFactory dfactory =

 

javax.xml.parsers.DocumentBuilderFactory.newInstance();

 

dfactory.setNamespaceAware(true);

 

javax.xml.parsers.DocumentBuilder docBuilder = dfactory.newDocumentBuilder();

 

org.w3c.dom.Document doc = docBuilder.newDocument();

 

Element root = doc.createElement(rootName);

 

doc.appendChild(root);

 

return doc;

 

}catch(Exception e)

 

{

 

System.out.println("Error in createXMLDocument" + e.getMessage());

 

throw new Exception ("Error in createXMLDocument" + e);

 

}

 

}

 

 

Parsing XML

The response returned from UPS XML Online Tools is a String in XML format. A customer application to process the XML response is needed. Here is a sample XML response returned from the UPS OnLine Tools server.  

Parsing XML with IBM's API

IBM's XML4J is a 100% pure Java solution for building XML document and parse XML, and is available for both Java1 and Java2 VM. Refer to the API documentation from alphaworks for more information on XML4J http://alphaworks.ibm.com.

 

Code Example

Using XML4J, an XML string can be parsed into a usable DOM object as seen in the code example below:

 

protected Document getDocument(String adaptee) throws Exception

 

{

 

com.ibm.xml.parsers.DOMParser parser = null;

 

org.w3c.dom.Document doc = null;

 

try

 

{

 

StringReader adapteeReader = new StringReader(adaptee);

 

InputSource input = new InputSource(adapteeReader);

 

//call IBM's XML4J parser

 

parser = new com.ibm.xml.parsers.DOMParser();

 

if (parser != null)

 

{

 

parser.parse(input);

 

doc = parser.getDocument();

 

}else

 

System.out.println("Failed to create a parser in getDocument.");

 

}

 

catch (SAXException sx)

 

{

 

Exception ex = sx.getException();

 

if (ex != null)

 

{

 

PrintStream stream = null;

 

ex.printStackTrace(stream);

 

}

 

else

 

{

 

PrintStream stream = null;

 

sx.printStackTrace(stream);

 

}

 

System.out.println("SAXException in getDocument.");

 

throw sx;

 

}

 

catch (FileNotFoundException fnf)

 

{

 

System.out.println(fnf.getMessage());

 

throw fnf;

 

}

 

catch (IOException ioe)

 

{

 

System.out.println(ioe.getMessage());

 

throw ioe;

 

}

 

return doc;

 

}

 

 

Parsing XML with Sun's API

Sun Microsystems provides a Java API for XML Parsing (JAXP). JAXP enables loose coupling between a vendor implementation and a Java application using JAXP's API's. With JAXP, a system property can be used to specify the parser to use instead of importing a vendor�s parser class directly in the code. In this way, changing the parser implementation to be used requires only a change to the system property specifying the parser class to JAXP without changing the application codes. For more information on JAXP, refer to http://java.sun.com/xml/.

 

Code Example

The method to parse an XML string into a usable DOM object with JAXP is illustrated below:

 

javax.xml.parsers.DocumentBuilderFactory dfactory =

 

javax.xml.parsers.DocumentBuilderFactory.newInstance();

 

dfactory.setNamespaceAware(true);

 

parser = dfactory.newDocumentBuilder();

 

org.w3c.dom.Document doc = parser.parse(input);

 

The following example shows how to build a shipmenet object from a BufferString containing xml.

 

public ServiceResponseContainer adaptFromXml(StringBuffer xmlIn) throws Exception

 

{

 

try

 

{

 

Document doc = getDocument(xmlIn.toString());

 

org.w3c.dom.Node root = doc.getFirstChild();

 

org.w3c.dom.Node shipmentNode = null;

 

for (shipmentNode = getChildNode(root, XML_Shipment); shipmentNode != null;

shipmentNode = shipmentNode.getNextSibling())

 

{

 

if (shipmentNode.getNodeName().equalsIgnoreCase(XML_Shipment))

 

{

 

Shipment ship = new Shipment();

 

ship.setDescription(getChildNodeValue(shipmentNode, XML_Description));

 

ship.setShipmentID(getChildNodeValue(shipmentNode,XML_Shipment IdentificationNumber));

 

ship.setDeliveryZone(getChildNodeValue(shipmentNode, XML_DeliveryZone));

 

ship.setPickupDate(getChildNodeValue(shipmentNode, XML_PickupDate));

 

 

}

 

}

 

 

}

 

 

The sample class Adapter provides complete methods to build XML document, and parse XML using XML4J and for Java 1.1.x .

 

 

Return to Top

 

Copyright � 2006 United Parcel Service of America, Inc.