DOM
Download
1 / 63

DOM - PowerPoint PPT Presentation


  • 58 Views
  • Uploaded on

DOM. DOM: Document Object Model from Dietel chapter 8. XML when parsed is represented as a tree structure in memory with elements attributes and content as tree nodes. XML is dynamic, a programmer can add or remove data, query for data as you would with a database.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' DOM' - kaitlin-dennis


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Dom document object model from dietel chapter 8
DOM: Document Object Model from Dietel chapter 8

  • XML when parsed is represented as a tree structure in memory with elements attributes and content as tree nodes.

  • XML is dynamic, a programmer can add or remove data, query for data as you would with a database.

  • W3C provides a document object model – a standard for constructing the tree in memory. A parser following this guideline in a DOM-parser.

  • A DOM parser exposes (makes available) a programmatic library that allows data in xml to be manipulated by manipulating the treenodes.


Ms xml 6 0 insert

MS XML 6.0 insert

Download available at ms

Note: Peltzer text uses DOM object 4.0 but I could only get 3.0 to work



A jscript
A jscript

<HTML>

<HEAD>

<TITLE>Displaying a Simple DOM Document in a Browser Popup</TITLE>

<SCRIPT LANGUAGE="JScript">

function displayXml() {

var xmldoc = new ActiveXObject("MSXML2.DOMDocument.3.0");

xmldoc.load("authors.xml");

alert(xmldoc.xml);

}

</SCRIPT>

</HEAD>

<BODY>

<BUTTON onClick="displayXml();">Display XML</BUTTON>

</BODY>

</HTML>


The xml from our peltzer text
The xml (from our Peltzer text)

<Authors>

<AuthorInfo>

<AuthorID>101</AuthorID>

<AuthorFName>Dwight</AuthorFName>

<AuthorLName>Peltzer</AuthorLName>

<AuthorAddress>PO Box 516</AuthorAddress>

<Auth_City>Some City</Auth_City>

<Au_State>NY</Au_State>

<Au_Zip>11564</Au_Zip>

<BusinessTelNo>516-111-1234</BusinessTelNo>

<Title>Professor of Computer Science</Title>

<Employer>Tech University</Employer>

</AuthorInfo>

<AuthorPublisherInfo>

<Publisher>Addison Wesley</Publisher>

<Editor>MSR</Editor>

<Address>25 Main Street Street</Address>

<City>Major City</City>

<State>MA</State>

</AuthorPublisherInfo>

<BookInfo>

<Title>XML Language Mechanics</Title>

<Pages> 450</Pages>

<PublishDate>Summer 2003</PublishDate>

<ISBN>0-201-77168-3</ISBN>

<Category>XML Markup Language</Category>

<NumChapters>12</NumChapters>

<AdditionalFeatures>Self-Review Exercises and Projects</AdditionalFeatures>

<SoftwareTools>Evaluation copy of XML Spy</SoftwareTools>

</BookInfo>

</Authors>




In javascript use loadxml to load a file or a string into activexobject domdocument
In Javascript, use loadXML to load a file or a string into ActiveXObject (DOMDocument)

<HTML>

<HEAD>

<TITLE>Displaying a Simple DOM Document in a Browser Popup</TITLE>

<SCRIPT LANGUAGE="JScript">

function displayXml() {

var xmldoc = new ActiveXObject("MSXML2.DOMDocument.3.0");

xmldoc.loadXML("<root><child></child></root>");

alert(xmldoc.xml);

}

</SCRIPT>

</HEAD>

<BODY>

<BUTTON onClick="displayXml();">Display XML</BUTTON>

</BODY>

</HTML>


Example script
Example script ActiveXObject (DOMDocument)

<html>

<body>

<script language="JavaScript">

objDOM = new ActiveXObject("Msxml2.DOMDocument.3.0");

objDOM.async = false;

var objNode;

var objText;

objNode = objDOM.createElement("root");

objText = objDOM.createTextNode(" root AuthorElement");

objDOM.appendChild(objNode);

objNode.appendChild(objText);

alert(objDOM.xml);

</script>

</body>

</html>



Javascript to display nodes and content
Javascript to display nodes and content ActiveXObject (DOMDocument)

<html>

<body>

<script type="text/vbscript">

Text="<h1>Pastry 4 U</h1>"

document.write(Text)

set xmlDoc=CreateObject("Msxml2.DOMDocument.3.0")

xmlDoc.async="false"

xmlDoc.load("pastry.xml")

for each n in xmlDoc.documentElement.childNodes

document.write(n.nodename)

document.write(": ")

document.write(n.text)

document.write("<br>")

next

</script>

</body>

</html>


Running on pastry xml
Running on pastry.xml ActiveXObject (DOMDocument)


Another example to display note contents
Another example to display note contents ActiveXObject (DOMDocument)


The script
The script ActiveXObject (DOMDocument)

<html>

<head>

<SCRIPT LANGUAGE="JScript">

function displayXml() {

var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0")

xmlDoc.async="false"

xmlDoc.load("note.xml")

to.innerText =

xmlDoc.getElementsByTagName("to").item(0).text

from.innerText=

xmlDoc.getElementsByTagName("from").item(0).text

header.innerText=

xmlDoc.getElementsByTagName("heading").item(0).text

body.innerText=

xmlDoc.getElementsByTagName("body").item(0).text

}

</script>

</head>

<body bgcolor="white">

<BUTTON onClick="displayXml();">Display XML</BUTTON>

<h1>DP Software</h1>

<b>To: </b>

<span id="to"></span>

<br>

<b>From: </b>

<span id="from"></span>

<hr>

<b><span id="header"></span></b>

<hr>

<span id="body"></span>

</body>

</html>


The note xml
The note(.xml) ActiveXObject (DOMDocument)

<note>

<to>

Bob

</to>

<from>

Joe

</from>

<heading>

important news!

</heading>

<body>

CSCI 345 assignment is due!!!

</body>

</note>



Script
script slide for script)

<html>

<head>

<title>DOM Invoice</title>

</head>

<body>

<script type="text/vbscript">

set xmlDoc = CreateObject("Msxml2.DOMDocument.3.0")

xmlDoc.async="false"

xmlDoc.load("authors.xml")

document.write("<h1>This is the root element</h1>")

alert(xmlDoc.documentElement.nodeName)

alert(xmlDoc.documentElement.childNodes(0).nodeName)

alert(xmlDoc.documentElement.childNodes.item(0).text)

</script>

</body>

</html>


Authors xml the rest in notes
Authors.xml…the rest in notes slide for script)

  • <Authors>

  • <AuthorInfo>

  • <AuthorID>101</AuthorID>

  • <AuthorFName>Dwight</AuthorFName>

  • <AuthorLName>Peltzer</AuthorLName>

  • <AuthorAddress>PO Box 516</AuthorAddress>

  • <Auth_City>Some City</Auth_City>

  • <Au_State>NY</Au_State>

  • <Au_Zip>11564</Au_Zip>

  • <BusinessTelNo>516-111-1234</BusinessTelNo>

  • <Title>Professor of Computer Science</Title>

  • <Employer>Tech University</Employer>



The xml
The xml slide for script)

<root>

<TeacherElement>CSCI</TeacherElement>

<TeacherFName>Dennis</TeacherFName>

<TeacherLName>Higgins</TeacherLName>

<TeacherOffice>Fitzelle 239</TeacherOffice>

<TeacherPhone>3552</TeacherPhone>

</root>


Vbscript
vbscript slide for script)

<script type="text/vbscript">

set xmlDoc=CreateObject("Msxml2.DOMDocument.3.0")

xmlDoc.async="false"

xmlDoc.load("teacherinfo.xml")

document.write(xmlDoc.documentElement.childNodes(0).nodeName)

document.write(":")

document.write(xmlDoc.documentElement.childNodes(0).text)

document.write("<br />")

document.write(xmlDoc.documentElement.childNodes(0).nextSibling.nodeName)

document.write(":")

document.write(xmlDoc.documentElement.childNodes(0).nextSibling.text)

document.write("<br />")

document.write(xmlDoc.documentElement.childNodes(2).nodeName)

document.write(":")

document.write(xmlDoc.documentElement.childNodes(2).text)

document.write("<br />")

document.write(xmlDoc.documentElement.childNodes(3).nodeName)

document.write(":")

document.write(xmlDoc.documentElement.childNodes(3).text)

document.write("<br />")

document.write(xmlDoc.documentElement.childNodes(4).nodeName)

document.write(":")

document.write(xmlDoc.documentElement.childNodes(4).text)

document.write("<br />")

</script>


Create an entire document
Create an entire document slide for script)


The javascript
The javascript slide for script)

<HTML>

<HEAD><TITLE>DOM Demo</TITLE>

<SCRIPT language="JavaScript">

var objDOM;

objDOM = new ActiveXObject("Msxml2.DOMDocument.3.0");

objDOM.async = false;

var objNode;

var objFragment;

<!-- create root element-->

objNode = objDOM.createElement("root");

objDOM.appendChild(objNode);

<!-- create the Document Interface Object to which other objects can be added -->

objFragment = objDOM.createDocumentFragment();

<!-- Now create all child elements -->

objNode = objDOM.createElement("FName");

<!-- append the child node -->

objFragment.appendChild(objNode);

<!-- create the text node for the child elements; Note the firstChild specifier -->

objFragment.firstChild.appendChild(objDOM.createTextNode("Dennis"));

objNode = objDOM.createElement("LName");

objFragment.appendChild(objNode);

objFragment.lastChild.appendChild(objDOM.createTextNode("Higgins"));

objNode = objDOM.createElement("Publisher");

objFragment.appendChild(objNode);

objFragment.lastChild.appendChild(objDOM.createTextNode("WhoKnowzPress"));

objNode = objDOM.createElement("Address");

objFragment.appendChild(objNode);

objFragment.lastChild.appendChild(objDOM.createTextNode("592 Cty Rte 5"));

objNode = objDOM.createElement("City");

objFragment.appendChild(objNode);

objFragment.lastChild.appendChild(objDOM.createTextNode("Otego"));

objNode = objDOM.createElement("State");

objFragment.appendChild(objNode);

objFragment.lastChild.appendChild(objDOM.createTextNode("NY"));

objNode = objDOM.createElement("ZipCode");

objFragment.appendChild(objNode);

objFragment.lastChild.appendChild(objDOM.createTextNode("13825"));

<!-- Finally add the elements to our document root element -->

objDOM.documentElement.appendChild(objFragment);

alert(objDOM.xml);

</SCRIPT>

</HEAD>

<BODY>

<P>Building an XML Document.</P>

</BODY>

</HTML>


Linked at
Linked at… slide for script)


Dom from javascript
DOM from javascript slide for script)


A javascript form slide 1
A Javascript form: slide 1 slide for script)

  • The javascript code is in notes for this slideLink is: http://employees.oneonta.edu/higgindm/internet%20programming/jsDataFromForm2.html


A javascript form slide 2
A Javascript form: slide 2 slide for script)


Dom structure using javascript dom html
DOM structure using javascript slide for script)DOM.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<title>A DOM Example</title>

</head>

<body>

<script type = "text/javascript" language = "JavaScript">

var xmlDocument = new ActiveXObject( "Microsoft.XMLDOM" );

xmlDocument.load( "article.xml" );

// get the root element

var element = xmlDocument.documentElement;

document.writeln(

"<p>Here is the root node of the document:" );

document.writeln( "<strong>" + element.nodeName

+ "</strong>" );

document.writeln(

"<br>The following are its child elements:" );

document.writeln( "</p><ul>" );

// traverse all child nodes of root element

for ( i = 0; i < element.childNodes.length; i++ ) {

var curNode = element.childNodes.item( i );

// print node name of each child element

document.writeln( "<li><strong>" + curNode.nodeName

+ "</strong></li>" );

}


Dom html file continued
DOM.html file continued slide for script)

document.writeln( "</ul>" );

// get the first child node of root element

var currentNode = element.firstChild;

document.writeln( "<p>The first child of root node is:" );

document.writeln( "<strong>" + currentNode.nodeName

+ "</strong>" );

document.writeln( "<br>whose next sibling is:" );

// get the next sibling of first child

var nextSib = currentNode.nextSibling;

document.writeln( "<strong>" + nextSib.nodeName

+ "</strong>." );

document.writeln( "<br>Value of <strong>" + nextSib.nodeName

+ "</strong> element is:" );

var value = nextSib.firstChild;

// print the text value of the sibling

document.writeln( "<em>" + value.nodeValue + "</em>" );

document.writeln( "<br>Parent node of " );

document.writeln( "<strong>" + nextSib.nodeName

+ "</strong> is:" );

document.writeln( "<strong>" + nextSib.parentNode.nodeName

+ "</strong>.</p>" );

</script>

</body>

</html>


Running dom html on article xml
Running DOM.html on article.xml slide for script)

<?xml version = "1.0"?>

<!-- Fig. 8.2: article.xml -->

<!-- Article formatted with XML -->

<article>

<title>Simple XML</title>

<date>December 6, 2000</date>

<author>

<fname>Tem</fname>

<lname>Nieto</lname>

</author>

<summary>XML is pretty easy.</summary>

<content>Once you have mastered HTML, XML is easily

learned. You must remember that XML is not for

displaying information but for managing information.

</content>

</article>


Running dom html opens article xml
Running DOM.html slide for script)(opens article.xml)


Javascript
javascript slide for script)

  • modification of javascript program in Deitel text (in notes) lists children of root element and children of each of these.

  • run on myclass.xml database



Replacing text in an xml document and rewriting the file
Replacing text in an xml document and rewriting the file slide for script)

  • Dietel frequently uses the class com.sun.xml.tree.XmlDocument. This class is not part of java and you may (will!) have a hard time getting hold of it. It is nice, because it can be cast as a PrintWriter to write an xml file out. However, it is purposely not included in java because it is an internal class and subject to change. I figured out another way to do this using the transformer class, which is part of java. My way, unfortunately uses more code, so there is room for improvement.

  • My code appears in the notes. Here are the two changes to the text version:

  • In header:

    import javax.xml.transform.*;

    import javax.xml.transform.dom.DOMSource;

  • In code, to write file

    StreamResult result = new StreamResult(new FileOutputStream("tmp.xml"));

    transformer.transform(source, result);


Original and rewritten xml

Original: slide for script)

<?xml version="1.0" encoding="UTF-8"?>

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

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

<!DOCTYPE myMessage

[

<!ELEMENT myMessage ( message )>

<!ELEMENT message ( #PCDATA )>

]>

<myMessage>

<message>New Changed Message!!</message>

</myMessage>

New version. BTW, LFs are not in file!!!

<?xml version="1.0" encoding="UTF-8"?>

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

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

<myMessage>

<message>some string</message>

</myMessage>

Original and rewritten xml


A java program to create an xml file buildxml java
A java program to create an xml file slide for script)BuildXML.java

  • The java program in notes creates the xml file (tmp2.xml) below. Uses transformer instead of XMLDocument class.

    <?xml version="1.0" encoding="UTF-8"?>

    <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>


Traversing the dom tree with a java program input file
Traversing the DOM tree with a java program: Input file slide for script)

  • Uses the xml file simpleContact.xml

    <?xml version = "1.0"?>

    <!-- Fig 8.17 : simpleContact.xml -->

    <!-- Input file for traverseDOM.java -->

    <!DOCTYPE contacts [

    <!ELEMENT contacts ( contact+ )>

    <!ELEMENT contact ( FirstName, LastName )>

    <!ATTLIST contact gender ( M | F ) "M">

    <!ELEMENT FirstName ( #PCDATA )>

    <!ELEMENT LastName ( #PCDATA )>

    ]>

    <contacts>

    <contact gender = "M">

    <FirstName>John</FirstName>

    <LastName>Black</LastName>

    </contact>

    <contact gender = "F">

    <FirstName>Johanna</FirstName>

    <LastName>Nally</LastName>

    </contact>

    </contacts>

    <!---->


Commandline
Commandline slide for script)

  • Java TraverseDOM simpleContact.xml


Traversing the dom tree with a java program output
Traversing the DOM tree with a java program: Output slide for script)

C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>java TraverseDOM simpleContact.xml

Document node: #document

Root element: contacts

Element node: contacts

Element node: contact

Attribute: gender ; Value = M

Element node: FirstName

Text: John

Element node: LastName

Text: Black

Element node: contact

Attribute: gender ; Value = F

Element node: FirstName

Text: Johanna

Element node: LastName

Text: Nally

C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>



Dayplanner using dom
DayPlanner using DOM slide for script)

  • The next example revisits the DayPlanner example (modified to use DOM)

  • Examples from Deitel XML, examples, 8_18 directory.


Domecho02 uses jtree to display dom tree structure
DOMEcho02 uses JTree to display DOM tree structure slide for script)

  • Usage is

  • Path>java DOMEcho02 file.xml

  • Listing in notes



Dayplanner using dom1
DayPlanner using DOM slide for script)


Mytransformer another java program
MyTransformer, another java program slide for script)

  • This program parses the xml, generates errors if any, displays the data content.

  • MyTransformer appears in notes

  • To run:

    Path>java MyTransformer input.xml output.xyz


Mytransformer another java program input
MyTransformer, another java program:input slide for script)

<?xml version = "1.0"?>

<!-- Fig 8.17 : simpleContact.xml -->

<!-- Input file for traverseDOM.java -->

<!DOCTYPE contacts [

<!ELEMENT contacts ( contact+ )>

<!ELEMENT contact ( FirstName, LastName )>

<!ATTLIST contact gender ( M | F ) "M">

<!ELEMENT FirstName ( #PCDATA )>

<!ELEMENT LastName ( #PCDATA )>

]>

<contacts>

<contact gender = "M">

<FirstName>John</FirstName>

<LastName>Black</LastName>

</contact>

<contact gender = "F">

<FirstName>Johanna</FirstName>

<LastName>Nally</LastName>

</contact>

</contacts>

<!---->


Mytransformer another java program output
MyTransformer, another java program:output slide for script)

<?xml version="1.0" encoding="UTF-8"?><!-- Fig 8.17 : simpleContact.xml --><!-- Input file for MyTransformer.java --><contacts>

<contact gender="M">

<FirstName>John</FirstName>

<LastName>Black</LastName>

</contact>

<contact gender="F">

<FirstName>Johanna</FirstName>

<LastName>Nally</LastName>

</contact>

</contacts><!---->




The next few slides
The next few slides notes

  • The contents of the next several slides appear in the notes of this ppt but are shown here in their entirety.

  • They show an errorhandler class and all the code to traverse a DOM structure.

  • Code is from Deitel.


Errorhandler
ErrorHandler notes

import org.xml.sax.ErrorHandler;

import org.xml.sax.SAXException;

import org.xml.sax.SAXParseException;

public class MyErrorHandler implements ErrorHandler

{

// throw SAXException for fatal errors

public void fatalError( SAXParseException exception )

throws SAXException

{ throw exception; }

public void error( SAXParseException e )

throws SAXParseException

{ throw e; }

// print any warnings

public void warning( SAXParseException err )

throws SAXParseException

{ System.err.println( "Warning: " + err.getMessage() ); }

}


Imports for traversedom
Imports for TraverseDOM notes

import java.io.*;

import org.w3c.dom.*;

import org.xml.sax.*;

import javax.xml.parsers.*;

import com.sun.xml.tree.XmlDocument;

  • Last import is not part of java

  • You will have to use my notes in previous slides on how to write out a DOM document to a file.


Traversedom
TraverseDOM notes

public class TraverseDOM {

private Document document;

public TraverseDOM( String file )

{ try {

// obtain the default parser

DocumentBuilderFactory factory =

DocumentBuilderFactory.newInstance();

factory.setValidating( true );

DocumentBuilder builder = factory.newDocumentBuilder();

// set error handler for validation errors

builder.setErrorHandler( new MyErrorHandler() );

// obtain document object from XML document

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 \'"

+ file + "\' not found. " );

System.exit( 1 );

}

catch ( Exception e ) { e.printStackTrace(); } }


Processnode
processNode notes

public void processNode( Node currentNode )

{ switch ( currentNode.getNodeType() ) {

// process a Document node

case Node.DOCUMENT_NODE:

Document doc = ( Document ) currentNode;

System.out.println(

"Document node: " + doc.getNodeName() +

"\nRoot element: " +

doc.getDocumentElement().getNodeName() );

processChildNodes( doc.getChildNodes() );

break;

// process an Element node

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;

// process a text node and a CDATA section

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; } }


Processchildnodes
processChildNodes notes

public void processChildNodes( NodeList children )

{

if ( children.getLength() != 0 )

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

processNode( children.item( i ) );

}

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 ] );

}

}


Installing jdom
Installing JDOM notes

  • Read the readme file

  • Run ant build

  • Copy jdom.jar where you want it

  • Edit classpath environment var from control panel/system/advanced/ to contain

    Path…\org\jdom\jdom.jar


Xsltransform in jdom samples prints html to output this is just some of the output
XSLTransform in JDOM samples prints html to output (this is just some of the output)

C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>java XSLTransform catalog.xml catalog.xsl

<?xml version="1.0" encoding="UTF-8"?>

<html>

<head>

<title>Small chamber ensembles - 2-4 Players by New York Women Composers</ti

tle>

</head>

<body>

<h1>Small chamber ensembles - 2-4 Players by New York Women Composers</h1>

<h3>Trio for Flute, Viola and Harp</h3>

<ul>

<li>(1994)</li>

<li>13'38"</li>

<li>fl, hp, vla</li>

<li>Theodore Presser</li>

</ul>

<p>Premiered at Queens College in April, 1996 by Sue Ann Kahn,

Christine Ims, and Susan Jolles. In 3 movements :

mvt. 1: 5:01

mvt. 2: 4:11

mvt. 3: 4:26</p>

<h3>Charmonium</h3>

<ul>

<li>(1991)</li>

<li>9'</li>

<li>2 vln, vla, vc</li>

<li />

</ul>

<p>Commissioned as quartet for the Meridian String Quartet.

Sonorous, bold. Moderate difficulty. Tape available.</p>

<h3>Invention for Flute and Piano</h3>

<ul>

<li>(1994)</li>

<li />

<li>fl, pn</li>

<li />

</ul>


Jdom comes with many demo programs here is some of the descendantdemo output
JDOM comes with many demo programs: here is some of the DescendantDemo output

C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>java DescendantDemo web.xml

All content:

[Comment: <!--

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">

-->]

[Element: <web-app/>]

[Text:

]

[Element: <servlet/>]

[Text:

]

[Element: <servlet-name/>]

[Text:

snoop

]

[Text:

]

[Element: <servlet-class/>]

[Text:

SnoopServlet

]

[Text:

]

[Text:

]

[Element: <servlet/>]

[Text:

]

[Element: <servlet-name/>]

[Text:

file

]

[Text:

]


Continued
continued DescendantDemo output

<servlet-mapping>

<servlet-name>

mv

</servlet-name>

<url-pattern>

*.wm

</url-pattern>

</servlet-mapping>

<distributed />

<security-role>

<role-name>

manager

</role-name>

<role-name>

director

</role-name>

<role-name>

president

</role-name>

</security-role>

</web-app>

C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>


Saxbuilder output run on birds xml in notes how to build a jdom from a sax parser example
SAXBuilder output (run on birds.xml in notes): How to build a JDOM from a SAX parser example

C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>java SAXBuilderDemo birds.xml true

<?xml version="1.0" encoding="UTF-8"?>

<Class>

<Order Name="TINAMIFORMES">

<Family Name="TINAMIDAE">

<Species Scientific_Name="Tinamus major">Great Tinamou.</Species>

<Species Scientific_Name="Nothocercus">Highland Tinamou.</Species>

<Species Scientific_Name="Crypturellus soui">Little Tinamou.</Species>

<Species Scientific_Name="Crypturellus cinnamomeus">Thicket Tinamou.</Spec

ies>

<Species Scientific_Name="Crypturellus boucardi">Slaty-breasted Tinamou.</

Species>

<Species Scientific_Name="Crypturellus kerriae">Choco Tinamou.</Species>

</Family>

</Order>


Saxbuilder code
SAXBuilder code a JDOM from a SAX parser example

import java.io.*;

import org.jdom.*;

import org.jdom.input.*;

import org.jdom.output.*;

/**

* <p><code>SAXBuilderDemo</code> demonstrates how to

* build a JDOM <code>Document</code> using a SAX 2.0

* parser.

* </p>

*/

public class SAXBuilderDemo {

/**

* <p>

* This provides a static entry point for creating a JDOM

* <code>{@link Document}</code> object using a SAX 2.0

* parser (an <code>XMLReader</code> implementation).

* </p>

*

* @param args <code>String[]</code>

* <ul>

* <li>First argument: filename of XML document to parse</li>

* <li>Second argument: optional boolean on whether to expand

* entities</li>

* <li>Third argument: optional String name of a SAX Driver class

* to use</li>

* </ul>

*/


Saxbuilder cont
SAXBuilder cont. a JDOM from a SAX parser example

public static void main(String[] args) {

if ((args.length < 1) || (args.length > 3)) {

System.out.println(

"Usage: java SAXBuilderDemo " +

"[XML document filename] ([expandEntities] [SAX Driver Class])");

return;

}

boolean expandEntities = true;

// Load filename and SAX driver class

String filename = args[0];

String saxDriverClass = null;

if (args.length > 1) {

if (args[1].equalsIgnoreCase("false")) {

expandEntities = false;

}

if (args.length > 2) {

saxDriverClass = args[2];

}

}

// Create an instance of the tester and test

try {

SAXBuilder builder = null;

if (saxDriverClass == null) {

builder = new SAXBuilder();

} else {

builder = new SAXBuilder(saxDriverClass); }

builder.setExpandEntities(expandEntities);

Document doc = builder.build(filename);

XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());

//outputter.setExpandEmptyElements(true);

outputter.output(doc, System.out);

} catch (JDOMException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace(); } }}


ad