34
JAVA API FOR XML DOM

java API for XML DOM

Embed Size (px)

Citation preview

Page 1: java API for XML DOM

JAVA API FOR XML DOM

Page 2: java API for XML DOM

Introduction

Java WSDP: Java Web Services Developer Pack

Document-oriented Java API are:– Java API for XML Processing (JAXP)

processes XML documents using various parsers

– Java Architecture for XML Binding (JAXB) processes XML documents using schema-

derived JavaBeans component classes

Page 3: java API for XML DOM

DOM Classes and Interfaces

Class/Interface Description

Document interface Represents the XML document’s top-level node, which provides access to all the document’s nodes—including the root element.

Node interface Represents an XML document node.

NodeList interface Represents a read-only list of Node objects.

Element interface Represents an element node. Derives from Node.

Attr interface Represents an attribute node. Derives from Node.

CharacterData interface Represents character data. Derives from Node.

Text interface Represents a text node. Derives fromCharacterData.

Page 4: java API for XML DOM

DOM API of JAXP

Package Description

org.w3c.dom Defines the DOM programming interfaces for XML documents, as specified by the W3C.

javax.xml.parsers

Provides classes related to parsing an XML document.DocumentBuilderFactory class and the DocumentBuilder class,returns an object that implements the W3C Document interface. This package also defines the ParserConfigurationException class forreporting errors.

Page 5: java API for XML DOM

Outline

XML Doc.

Document Builder

Document Builder Factory

DOM

Page 6: java API for XML DOM

Simple DOM program, I

import javax.xml.parsers.*;

import org.w3c.dom.*;

public class SecondDom { public static void main(String args[]) { try { ...Main part of program goes here... } catch (Exception e) { e.printStackTrace(System.out); } }}

Page 7: java API for XML DOM

Simple DOM program, II

First we need to create a DOM parser, called a “DocumentBuilder”.

Class DocumentBuilder provides a standard interface to an XML parser.

The parser is created, not by a constructor, but by calling a static factory method

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Page 8: java API for XML DOM

Simple DOM program, III

The next step is to load in the XML file Here is the XML file, named hello.xml:

<?xml version="1.0"?> <display>Hello World!</display>

To read this file in, we add the following line to our program:

Document document = builder.parse("hello.xml");

Notes:– document contains the entire XML file (as a tree); it is the

Document Object Model– If you run this from the command line, your XML file should be in

the same directory as your program

Page 9: java API for XML DOM

Simple DOM program, IV

The following code finds the content of the root element and prints it:

Element root = document.getDocumentElement(); Node textNode = root.getFirstChild(); System.out.println(textNode.getNodeValue());

The output of the program is: Hello World!

Page 10: java API for XML DOM

Reading in the tree

The parse method reads in the entire XML document and represents it as a tree in memory

If parsing is successful, a Document object is returned that contains nodes representing

each part of the intro.xml document.– If you want to interact with your program while it is

parsing, you need to parse in a separate thread» Once parsing starts, you cannot interrupt or stop it» Do not try to access the parse tree until parsing is done

An XML parse tree may require up to ten times as much memory as the original XML document

Page 11: java API for XML DOM

Other required Packages

Package Description

com.sun.xml.tree contains classes and interfaces from Sun Microsystem’sinternal XML API, which provides features currently not available in the XML 1.0 recommendation

org.xml.sax provides the Simple API for XML programmatic interface. A DOM-based parser may use an event-based implementation (such as Simple API for XML) to help create the tree structure in memory.

Page 12: java API for XML DOM

intro.xml

<?xml version = "1.0"?>

<!-- Fig. 8.12 : intro.xml -->

<!-- Simple introduction to XML markup -->

<!DOCTYPE myMessage [

<!ELEMENT myMessage ( message )>

<!ELEMENT message ( #PCDATA )>

]>

<myMessage>

<message>Welcome to XML!</message>

</myMessage>

Page 13: java API for XML DOM

MODIFYING XML DOCUMENT WITH DOM

Page 14: java API for XML DOM

import java.io.*;import org.w3c.dom.*;import javax.xml.parsers.*;import com.sun.xml.tree.XmlDocument;import org.xml.sax.*;

public class ReplaceText {

private Document document; public ReplaceText() { try { // obtain the default parser DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // set the parser to validating factory.setValidating( true );

Page 15: java API for XML DOM

DocumentBuilder builder = factory.newDocumentBuilder();

// set error handler for errors related to parsing

builder.setErrorHandler( new MyErrorHandler() );

// obtain document object from XML document document = builder.parse(

new File( "intro.xml" ) );

// fetch the root node Node root =

document.getDocumentElement();

Page 16: java API for XML DOM

if ( root.getNodeType() == Node.ELEMENT_NODE ) {

Element myMessageNode = ( Element ) root; NodeList messageNodes =

myMessageNode.getElementsByTagName( "message" );

if ( messageNodes.getLength() != 0 ) {//item() returns type Object and need casting

Node message = messageNodes.item( 0 ); // create a text node Text newText =

document.createTextNode("New Message!!" );

Cast root node as element (subclass), then get list of all

message elements

Page 17: java API for XML DOM

// get the old text node Text oldText =

( Text )message.getChildNodes().item( 0 ); // replace the text message.replaceChild( newText, oldText }} //Write new XML document to intro1.xml( (XmlDocument) document).write( new FileOutputStream("intro1.xml" ) ); }

Page 18: java API for XML DOM

catch ( SAXParseException spe ) { System.err.println( "Parse error: " + spe.getMessage() ); System.exit( 1 ); } catch ( SAXException se ) { se.printStackTrace(); } catch ( FileNotFoundException fne ) { System.err.println( “XML File not found. " ); System.exit( 1 ); } catch ( Exception e ) { e.printStackTrace(); } }

Page 19: java API for XML DOM

public static void main( String args[] ) { ReplaceText d = new ReplaceText(); }}

Page 20: java API for XML DOM

Building an XML Document with DOM

Page 21: java API for XML DOM

Desired Output<root> <!--This is a simple contact list--> <contact gender="F"> <FirstName>Sue</FirstName> <LastName>Green</LastName> </contact> <?myInstruction action silent?> <![CDATA[I can add <, >, and ?]]></root>

Page 22: java API for XML DOM

import java.io.*;import org.w3c.dom.*;import org.xml.sax.*;import javax.xml.parsers.*;import com.sun.xml.tree.XmlDocument;

public class BuildXml { private Document document;

public BuildXml() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

Page 23: java API for XML DOM

try { // get DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // create root node document = builder.newDocument(); } catch ( ParserConfigurationException pce ) { pce.printStackTrace(); }

Page 24: java API for XML DOM

Element root = document.createElement( "root" );

document.appendChild( root ); Comment simpleComment =document.createComment(

"This is a simple contact list" ); root.appendChild( simpleComment );

Node contactNode = createContactNode( document );

root.appendChild( contactNode ); ProcessingInstruction pi = document.createProcessingInstruction( "myInstruction", "action silent" );

root.appendChild( pi ); CDATASection cdata =

document.createCDATASection( "I can add <, >, and ?" ); root.appendChild( cdata );

Page 25: java API for XML DOM

try { // write the XML document to a file

( (XmlDocument) document).write( new

FileOutputStream("myDocument.xml" ) ); } catch ( IOException ioe ) { ioe.printStackTrace(); } }

Page 26: java API for XML DOM

public Node createContactNode( Document document ) { Element firstName =

document.createElement( "FirstName" ); firstName.appendChild(

document.createTextNode( "Sue" ) ); Element lastName =

document.createElement( "LastName" ); lastName.appendChild(

document.createTextNode( "Green" ) ); Element contact =

document.createElement( "contact" );Attr genderAttribute =

document.createAttribute( "gender" ); genderAttribute.setValue( "F" ); contact.setAttributeNode( genderAttribute ); contact.appendChild( firstName ); contact.appendChild( lastName ); return contact; }

Page 27: java API for XML DOM

public static void main( String args[] ) { BuildXml buildXml = new BuildXml(); }}

Page 28: java API for XML DOM

Traversing the DOM

Page 29: java API for XML DOM

import org.w3c.dom.*;import org.xml.sax.*;import javax.xml.parsers.*;import com.sun.xml.tree.XmlDocument;

public class TraverseDOM { private Document document; public TraverseDOM( String file ) { try {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

factory.setValidating( true ); DocumentBuilder builder =

factory.newDocumentBuilder();builder.setErrorHandler( new MyErrorHandler() );

Page 30: java API for XML DOM

document = builder.parse( new File( file ) ); processNode( document ); } catch ( SAXParseException spe ) { System.err.println("Parse error: " +

spe.getMessage() ); System.exit( 1 ); } catch ( SAXException se ) { se.printStackTrace(); } catch ( FileNotFoundException fne ) { System.err.println( "File not found. " ); System.exit( 1 ); } catch ( Exception e ) { e.printStackTrace();} }

Page 31: java API for XML DOM

public void processNode( Node currentNode ){ switch ( currentNode.getNodeType() ) {

case Node.DOCUMENT_NODE: Document doc = ( Document ) currentNode; System.out.println( Document node: " + doc.getNodeName() +

"\nRoot element: " + doc.getDocumentElement().getNodeName() );

processChildNodes( doc.getChildNodes() );

break;

Page 32: java API for XML DOM

case Node.ELEMENT_NODE: System.out.println( "\nElement node: " +

currentNode.getNodeName() );

NamedNodeMap attributeNodes = currentNode.getAttributes();

for (int i=0;i<attributeNodes.getLength();i++){

Attr attribute=(Attr)attributeNodes.item( i );

System.out.println( "\tAttribute: " + attribute.getNodeName() + " ;Value = "

attribute.getNodeValue() )

}

processChildNodes( currentNode.getChildNodes() );

break;

Page 33: java API for XML DOM

case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: Text text = ( Text ) currentNode; if ( !text.getNodeValue().trim().equals( "" ) ) System.out.println( "\tText: " +

text.getNodeValue() ); break; }}

public void processChildNodes( NodeList children ) { if ( children.getLength() != 0 ) for ( int i=0;i<children.getLength();i++) processNode(children.item(i) ); }

Page 34: java API for XML DOM

public static void main( String args[] ) { if ( args.length < 1 ) { System.err.println("Usage: java

TraverseDOM <filename>" ); System.exit( 1 ); } TraverseDOM traverseDOM = new

TraverseDOM( args[ 0 ] ); }}