Java XML Tutorial (with: source program)
Last Update:2017-02-28
Source: Internet
Author: User
xml| Program | Tutorial sonnet.xml This is the example XML documentation that is used throughout this tutorial. <?xml version= "1.0"?> <! doctype sonnet system "SONNET.DTD" > <sonnet type= "Shakespearean" > < author> <last-name>Shakespeare</last-name> <first-name>william</first-name > <nationality>British</nationality> <year-of-birth>1564</year-of-birth> <year-of-death>1616</year-of-death> </author> <title>sonnet 130 </title> <text> <line>my mistress ' eyes are nothing like the sun,</line> <line>coral is far more red than her lips red.</line> <line>If snow be white, why then her breasts are dun,</line> <line>if hairs be wires, black wires grow on her head.</line> <line>I have seen roses damasked, red and white,</line> <line>But no such roses see i in her cheeks.</line> <line>and in some perfumes is there more delight</line> <line>than in the breath that from my mistress reeks.</line> <line>I love to hear her speak, yet well i know</line> <line>That music hath a far more pleasing sound.</line> <line>i grant I never saw a goddess go,</line> <line>My mistress when she walks, treads on the ground.</line> <line>And yet , by heaven, I think my love as rare</line> <line>as any she belied with false compare.</line> </text> </sonnet> sonnet.dtd This is the &NBSP;DTD used in our sample documentation. <!-- sonnet.dtd --> <! element sonnet (author,title?,text) > <! attlist sonnet type (Shakespearean | petrarchan) "Shakespearean" > <! element text (line,line,line,line, line,line,line,line, line,line,line,line, Line, Line) > <! element author (last-name,first-name,nationality, Year-of-birth?,year-of-death?) > <! element title (<! element last-name (<! element first-name (<! element nationality (<! element year-of-birth (<! element year-of-death (<! element line (domone.java This is our first &nbs.p;dom applications. It parses a XML document and outputs its content to standard output. /* * (C) Copyright IBM Corp. 1999 All rights reserved. * * us government users restricted rights use, duplication or * disclosure restricted by gsa adp schedule contract with ibm corp. * * the program is provided "As is" without any warranty express or * implied, including the warranty of non-infringement and the implied * warranties of merchantibility and fitness for a particular purpose. * ibm will not be liable for any damages suffered by you as a result * of using the program. in no event will ibm be liable for any * special, indirect or consequential damages or lost profits even if * ibm has been advised of the possibility of their occurrence. IBM * will not be liable for any third party claims against you. */ import java.io.outputstreamwriter; import java.io.printwriter; import java.io.unsupportedencodingexception; import org.w3c.dom.attr; import org.w3c.dom.Document ; import org.w3c.dom.namednodemap; import org.w3c.dom.node; import org.w3c.dom.nodelist; import com.ibm.xml.parsers.*; /** * domOne.java * illustrates how to go through a dom tree. */ Public class domOne { PUBLIC&NBSp;void parseandprint (String uri) { document doc = null; try { Domparser parser = new domparser (); parser.parse (URI); doc = Parser.getdocument (); } catch (exception e) { System.err.println ("Sorry, an error occurred: " + e); } // we ' ve parsed the document now, so let ' s print it. if (doc != null) PrintDOMTree (DOC); } /** prints the specified node, then prints all of its children. */ Public void printdomtree (node node) { Int type = node.getnodetype (); switch (type) { // print the document element case node.document_node: { System.out.println ("<?xml version=" 1.0) ? > "); printdomtree ((Document) node). Getdocumentelement ()); break; } // print element with attributes case node.element_node: { System.out.print ("<"); System.out.print (Node.getnodename ()); namednodemap attrs = node.getattributes (); for (Int i = 0; i < attrs.getlength (); i++) { Node attr = attrs.item (i); System.out.print (" " + attr.getnodename () + "=" " + attr.getnodevalue () + " ""); } System.out.println (">"); Nodelist children = node.getchildnodes (); if (children != null) { Int len = children.getlength (); for (int i = 0; i < len; i++) Printdomtree (Children.item (i)); } break; } Entity reference nodes case node.entity_reference_node: { System.out.print ("&") ); System.out.print (Node.getnodename ()); System.out.print (";"); break; } // print cdata sections case node.cdata_section_node: { System.out.print ("<![ cdata["); System.out.print (Node.getnodevalue ()); System.out.print ("]]> "); break; } // print text case node.text_node: { System.out.print (Node.getnodevalue ()) ; break; } // print processing instruction case Node.PROCESSING_ instruction_node: { System.out.print ("A;?"); System.out.print (Node.getnodename ()); String data = node.getnodevalue (); { System.out.print (" "); System.out.print (data); } System.out.print ("?>"); break; } } if (type == nOde. Element_node) { System.out.println (); System.out.print ("</"); System.out.print ( Node.getnodename ()); System.out.print (' > '); } } /** main program entry point. */ Public static void main (string argv[]) { if ( argv.length == 0) { System.out.println ("Usage: java domone uri"); System.out.println (" where uri is the uri of the xml document you want to print. "); SYSTEM.OUT.PRINTLN (" sample: java domone sonnet.xml"); system.exit (1); } Domone d1 = new domone (); d1.parseandprint (argv[0); } domcounter.java This code parses a XML document, and then traverses the DOM tree to collect data about the document. When data is collected, it is output to standard output. /* * (C) copyright ibm corp. 1999 all rights reserved. * * us government users restricted rights use, duplication or * disclosure restricted by gsa adp schedule contract with ibm corp. * * the program is provided "As is" without any warranty express or * implied, including the warranty of non-infringement and the implied * warranties of merchantibility and fitness for a particular purpose. * IBM will not be liable for any damages suffered by you as a result *&NBSP;OF&NBSP;USING&NBSP;THE&NBSP;PROGRAM.&NBSP;IN&NBSP;NO&NBSP;EVENT&NBSP;WILL&NBSP;IBM be liable for any * special, indirect or consequential Damages or lost profits even if * ibm has been advised of the possibility of their occurrence. IBM * will not be liable for any third party claims against you. */ import java.io.outputstreamwriter; import java.io.printwriter; import java.io.unsupportedencodingexception; Import org.w3c.dom.Document; import org.w3c.dom.node; import org.w3c.dom.nodelist; import com.ibm.xml.parsers.domparser; /** * domcounter.java * This code creates a DOM parser, parses a document, then * prints statistics about the number and type of nodes * found in the document. */ public class domcounter { int documentNodes = 0;  int elementnodes = 0; int entityreferencenodes = 0; int cdatasections = 0; int textnodes = 0; int processinginstructions = 0; Public void parseandcount (String uri) { document doc = null; try { domparser parser = new domparser (); parser.parse (URI); Doc = parser.getdocument (); } catch (exception e) { System.err.println ("sorry, an error occurred: " + e); } // we ' ve parsed the document now, so let ' s scan the dom tree and // print the statistics. if (doc != null) { ScanDOMTree ( DOC); System.out.println ("document statistics for " + uri + ":"); System.Out.println ("===================================="); System.out.println ("document nodes: ") + documentnodes); System.out.println ("element nodes: " + elementnodes); SYSTEM.OUT.PRINTLN ("entity reference nodes: " + entityreferencenodes); System.out.println ("cdata sections: " + cdatasections); System.out.println ("Text Nodes: " + textnodes"; System.out.println ("processing instructions: ") + processinginstructions); System.out.println (" ----------"); int totalnodes = documentNodes + elementNodes + entityReferenceNodes + cdatasections + textNodes + processingInstructions; System.out.println ("total: " + totalnodes + " nodes"); } } /** scans the dom tree and counts the different types of nodes. */ Public void scandomtree (Node node) { Int type = node.getnodetype (); switch (type) { case node.document_node: documentnodes++; Scandomtree ((DOCUMENT) NODE. Getdocumentelement ()); break; case node.element_node: elementnodes++; nodelist children = Node.getchildnodes (); if (children != null) { int len = Children.getlength (); for (int i = 0; i < len; i++) Scandomtree (Children.item (i)); } break; case node.entity_reference_node: entityreferencenodes++; break; case node.cdata_section_node: cdataSections++; break; case node.text_node: textnodes++; break; Case node.processing_instruction_node: Processinginstructions++; break; } } /** main program entry point. */ public Static void main (string argv[]) { if (argv.length == 0) { System.out.println ("Usage: java domcounter uri"); System.out.println (" where uri is the uri of your xml document. "); SYSTEM.OUT.PRINTLN (" sample: java domcounter sonnet.xml"); system.exit (1); } domcounter dc = new domcounter (); Dc.parseandcount (argv[0]); } } Saxone.java/* * (C) copyright ibm corp. 1999 all rights reserved. * * us government users restricted rights use, duplication or * disclosure restricted by gsa adp schedule contract with ibm corp. *&NBsp * the program is provided "As is" without any warranty express or * implied, including the warranty of non-infringement and the implied * warranties of merchantibility and fitness for a particular purpose. * ibm will not be liable for any damages suffered by you as a result * of using the Program. In no event will IBM be liable for any * special, indirect or consequential damages or lost profits even if * ibm has been advised of the possibility of their occurrence. IBM * will not be liable for any third Party claims against you. */ import java.io.outputstreamwriter; import java.io.printwriter; import java.io.unsupportedencodingexception; import org.xml.sax.attributelist; import org.xml.sax.handlerbase; import org.xml.sax.parser; import org.xml.sax.saxexception; import org.xml.sax.saxparseexception; import org.xml.sax.helpers.parserfactory; import com.ibm.xml.parsers.saxparser; /** * saxone.java * this sample program illustrates how to use a sax parser. it * parses a document and writes the document? contents back to * standard output. */ Public class saxone extends handlerbase { Public void parseuri (string uri) { Saxparser parser = new sAxparser (); Parser.setdocumenthandler (This); Parser.seterrorhandler (this); try Parser.parse (URI); } catch (exception e) { System.err.println (e); } } /** processing instruction. */ public void processinginstruction (String target, string data) { System.out.print ("A;?"); System.out.print (target); if (Data != null && data.length () > 0) { System.out.print (' '); System.out.print (data); } ("?>"); } /** start document. */ public void startdocument () { SYSTEM.OUT.PRINTLN ("<?xml version=" 1.0 "?>"); } /** start element. */ Public void startelement (string name, attributelist attrs) { System.out.print ("<"); System.out.print (name); if (attrs != null) { int len = Attrs.getlength (); for (int i = 0; i < len; i++) { System.out.print (" "); System.out.print (Attrs.getname (i)); System.out.print ("="); System.out.print (Attrs.getvalue (i)); System.out.print ("" "); } -} System.out.print (" > "); } /** characters. */ public void characters (char ch[], int start, int length) { System.out.print (new string (ch, start, length)); } /** ignorable whitespace. */ Public void ignorablewhitespace (char ch [], int start, int length) { characters (ch, start, length); } /** end element. */ public void endelement (string name) { SystEm.out.print ("</"); System.out.print (name); System.out.print (">"); } document. */ public void enddocument () { // no need to do anything. } // // errorhandler methods // /** warning. */ public void warning (saxparseexception ex) { System.err.println ("[ warning] "+ getlocationstring (ex) +": "+ ex.getmessage ()); } . */ Public void error (saxparseexception ex) { System.err.println ("[ERROR] "+ getlocationstring (ex) +": "+ ex.getmessage ()); } . */ Public void fatalerror (Saxparseexception ex) throws saxexception { SYSTEM.ERR.PRINTLN ("[fatal error] " + getlocationstring (ex) + ": " + ex.getmessage ( )); throw ex; } /** returns a string of the location. */ Private string getlocationstring (Saxparseexception ex) { stringbuffer str = new stringbuffer (); string systemid = ex.getsystemid (); if ( Systemid != null) { int index = systemid.lastindexof ('/'); if ( index != -1) systemid = systemid.substring (index + 1); str.append ( SystemID); } str.append (': '); str.append (Ex.getlinenumber ()); str.append (': '); Str.append (Ex.getcolumnnumber ()); return str.tostring (); } /** main program entry point. */ Public static void main (string argv[]) { if (argv.length == 0) { System.out.println ("Usage: java saxone uri"); SyStem.out.println (" where uri is the uri of your xml document."); SYSTEM.OUT.PRINTLN (" sample: java saxone sonnet.xml"); system.exit (1); } Saxone s1 = new saxone (); S1.parseuri (argv[0); } saxcounter.java /* * (C) copyright ibm corp. 1999 all rights reserved. * * us government users restricted rights use, duplication or * disclosure restricted by gsa adp schedule contract with ibm corp. * * the program is provided "as" is " without any warranty express or * implied, including the warranty of non-infringement and the implied * warranties of merchantibility and fitness for a particular purpose. * ibm will not be liable for any damages suffered by you as a result * of using the program. in no event will ibm be liable for any * special, indirect or consequential damages or lost profits even if * ibm has been advised of the possibility of their occurrence. IBM * will not be liable for any third party claims against you. */ import java.io.outputstreamwriter; import java.io.printwriter; import java.io.unsupportedencodingexception; Import org.xml.sax.AttributeList; import org.xml.sax.handlerbase; Import org.xml.sax.parser ; Import org.xml.sax.saxexception; import org.xml.sax.saxparseexception; import org.xml.sax.helpers.parserfactory; import com.ibm.xml.parsers.saxparser; /** * saxcounter.java * this sample program calculates statistics for an XML document, * based on the sax events received. when the parse is complete, * it prints the statistics to standard output. */ public class saxcounter extends handlerbase { int startdocumentevents = 0; int enddocumentevents = 0; int startElementEvents = 0; int endelementevents = 0; int processinginstructionevents = 0; int characterevents = 0; int ignorablewhitespaceevents = 0; int warningevents = 0; int errorevents = 0; int fatalErrorEvents = 0; Public void parseuri (String uri) { saxparser parser = new saxparser (); Parser.setdocumenthandler (This); Parser.seterrorhandler (this); try { Parser.parse (URI); } catch (exception e) { System.err.println (e); } System.out.println ("document statistics for " + uri + ":"); SYSTEM.OUT.PRINTLN ("===================================="); System.out.println ("Documenthandler events: "); System.out.println (" startDocument " + startdocumentevents); System.out.println (" endDocument " + enddocumentevents); System.out.println (" startelement " + startelementevents); System.out.println (" endElement " +  endelementevents); System.out.println (" processingInstruction " + processinginstructionevents); System.out.println (" character " + characterevents); SYSTEM.OUT.PRINTLN (" ignorableWhitespace " + ignorablewhitespaceevents); System.out.println ("errorhandler events:"); System.out.println (" warning " + warningevents); System.out.println (" error " + errorevents); System.out.println ( " fatalError " + fatalerrorevents); System.out.println (" ----------"); int totalEvents = startDocumentEvents + endDocumentEvents + startelementevents + endElementEvents + processinginstructionevents + characterevents + ignorablewhitespaceevents + warningevents + errorevents + fatalerrorevents; System.out.prinTLN ("total: " + totalevents + " events"); } /** processing instruction. */ Public void processinginstruction (string target, string Data) { processinginstructionevents++; } /** start document. */ Public void startdocument () { startdocumentevents++; } /** start element. */ public void startelement (string name, attributelist attrs) { startelementevents++; } /** characters. */ public void characters (char ch[], int start, int length) { characterevents++; } /** ignorable whitespace. */ Public void ignorablewhitespace (char ch[], int start, int length) { ignorablewhitespaceevents++; } /** End Element. */ public void endelement (string name) { endelementevents++; } /** end document. */ public void enddocument () { enddocumentevents++; } // // errorhandler methods // /** Warning. */ public void warning (saxparseexception ex) { warningevents++; } /** error. */ Public void error (saxparseexception ex) { errorevents++; } /** fatal error. */ Public void fatalerror ( Saxparseexception ex) throws saxexception { fatalerrorevents++; throw ex; } /** main program entry point. */ public static void Main (string argv[]) { if (argv.length == 0) { System.out.println (" Usage: java saxcoUnter uri "); System.out.println (" where uri is the uri of your xml document. "); SYSTEM.OUT.PRINTLN (" sample: java saxcounter sonnet.xml"); system.exit (1); } saxcounter sc = new saxcounter (); Sc.parseuri (argv[0]); }