Java data access

Page 332

Chapter 18: Using XML with JAXP System.out.print(" SYSTEM "); } System.out.println(" " + docType.getSystemId() + ">"); break; //ATTRIBUTE_NODE = 2; //PROCESSING_INSTRUCTION_NODE = 7; //COMMENT_NODE = 8; //DOCUMENT_FRAGMENT_NODE = 11; //NOTATION_NODE = 12; default: break; } } // usage: java bookDescDOM bookDesc.xml public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: java bookDescDOM inputXMLfile"); System.exit(0); } String uri = args[0]; try { bookDescDOM bd = new bookDescDOM(); System.out.println("Parsing XML File: " + uri + "\n\n"); // Step 2: instantiate the vendors DOM parser // explicitly. DOMParser parser = new DOMParser(); parser.setFeature ("http://xml.org/sax/features/validation", true); parser.setFeature ("http://xml.org/sax/features/namespaces", false); parser.parse(uri); // Step 3. Acquire the document tree; for example via a getDocument() call. Document doc = parser.getDocument(); // Step 4. To process the document tree all we need to do is traverse // the tree a node at a time; using interfaces and classes provided by DOM. bd.processNode(doc, ""); } catch (Exception e) { e.printStackTrace(); System.out.println("Error: " + e.getMessage()); } } }

The following code is the output of this example; remember that the elements are printed as the DOM tree is traversed: C:\>java bookDescDOM bookDesc.xml Parsing XML File: d:\bookDesc.xml <!DOCTYPE myspace:book SYSTEM doc.dtd> <myspace:book xmlns:myspace= http://www.ournamespace.com> <title>Alice’s Adventures in Wonderland and Through the Looking Glass</title> <author> <first−name>Lewis</first−name> <last−name>Carroll</last−name> </author> <date> May 2000 </date> <internal identifier= 12345></internal> </myspace:book>

320


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.