Java Reference
In-Depth Information
protected
protected void
void outputCustomer ( OutputStream os , Customer cust )
throws
throws IOException {
PrintStream writer = new
new PrintStream ( os );
writer . println ( "<customer id=\"" + cust . getId () + "\">" );
writer . println ( " <first-name>" + cust . getFirstName ()
+ "</first-name>" );
writer . println ( " <last-name>" + cust . getLastName ()
+ "</last-name>" );
writer . println ( " <street>" + cust . getStreet () + "</street>" );
writer . println ( " <city>" + cust . getCity () + "</city>" );
writer . println ( " <state>" + cust . getState () + "</state>" );
writer . println ( " <zip>" + cust . getZip () + "</zip>" );
writer . println ( " <country>" + cust . getCountry () + "</country>" );
writer . println ( "</customer>" );
}
As you can see, this is a pretty straightforward method. Through string manipulations, it does
a brute-force conversion of the Customer object to XML text.
The next method is readCustomer() . The method is responsible for reading XML text from
an InputStream and creating a Customer object:
protected
protected Customer readCustomer ( InputStream is ) {
try
try {
DocumentBuilder builder =
DocumentBuilderFactory . newInstance (). newDocumentBuilder ();
Document doc = builder . parse ( is );
Element root = doc . getDocumentElement ();
Unlike outputCustomer() , we don't manually parse the InputStream . The JDK has a built-
in XML parser, so we do not need to write it ourselves or download a third-party library to
do it. The readCustomer() method starts off by parsing the InputStream and creating a
Java object model that represents the XML document. The rest of the readCustomer()
method moves data from the XML model into a newly created Customer object:
Customer cust = new
new Customer ();
iif ( root . getAttribute ( "id" ) != null
null
&& ! root . getAttribute ( "id" ). trim (). equals ( "" )) {
cust . setId ( Integer . valueOf ( root . getAttribute ( "id" )));
}
NodeList nodes = root . getChildNodes ();
for
for ( int
int i = 0 ; i < nodes . getLength (); i ++) {
Element element = ( Element ) nodes . item ( i );
iif ( element . getTagName (). equals ( "first-name" )) {
cust . setFirstName ( element . getTextContent ());
Search WWH ::




Custom Search