SlideShare a Scribd company logo
1 of 34
Download to read offline
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Document Object
Model
DOM
DOM2 www.corewebprogramming.com
Agenda
• Introduction to DOM
• Java API for XML Parsing (JAXP)
• Installation and setup
• Steps for DOM parsing
• Example
– Representing an XML Document as a JTree
• DOM or SAX?
DOM3 www.corewebprogramming.com
Document Object Model (DOM)
• DOM supports navigating and modifying
XML documents
– Hierarchical tree representation of document
• Tree follows standard API
• Creating tree is vendor specific
• DOM is a language-neutral specification
– Bindings exists for Java, C++, CORBA, JavaScript
• DOM Versions
– DOM 1.0 (1998)
– DOM 2.0 Core Specification (2000)
– Official Website for DOM
•http://www.w3c.org/DOM/
DOM4 www.corewebprogramming.com
DOM Tree
Document
Document Type Element
Element Element Attribute Attribute Text
Comment Text Text
Text Element Attribute Entity Reference
Text
DOM5 www.corewebprogramming.com
DOM Advantages and
Disadvantages
• Advantages
– Robust API for the DOM tree
– Relatively simple to modify the data structure and extract
data
• Disadvantages
– Stores the entire document in memory
– As DOM was written for any language, method naming
conventions don’t follow standard Java programming
conventions
DOM6 www.corewebprogramming.com
Java API for XML Parsing
(JAXP)
• JAXP provides a vendor-neutral interface to
the underlying DOM or SAX parser
javax.xml.parsers
DocumentBuilderFactory
DocumentBuilder
SAXParserFactory
SAXParser
ParserConfigurationException
FactoryConfigurationError
DOM7 www.corewebprogramming.com
DOM Installation and Setup
(JDK 1.4)
• All the necessary classes for DOM and
JAXP are included with JDK 1.4
• See javax.xml.* packages
• For DOM and JAXP with JDK 1.3 see
following viewgraphs
DOM8 www.corewebprogramming.com
DOM Installation and Setup
(JDK 1.3)
1. Download a DOM-compliant parser
• Java-based DOM parsers at
http://www.xml.com/pub/rg/Java_Parsers
• Recommend Apache Xerces-J parser at
http://xml.apache.org/xerces-j/
2. Download the Java API for XML
Processing (JAXP)
• JAXP is a small layer on top of DOM which supports
specifying parsers through system properties versus
hard coded
• See http://java.sun.com/xml/
• Note: Apache Xerces-J already incorporates JAXP
DOM9 www.corewebprogramming.com
DOM Installation and Setup
(continued)
3. Set your CLASSPATH to include the DOM
(and JAXP) classes
set CLASSPATH=xerces_install_dirxerces.jar;
%CLASSPATH%
or
setenv CLASSPATH xerces_install_dir/xerces.jar:
$CLASSPATH
• For servlets, place xerces.jar in the server’s lib
directory
• Note: Tomcat 4.0 is prebundled with xerces.jar
• Xerces-J already incorporates JAXP
• For other parsers you may need to add jaxp.jar
to your classpath and servlet lib directory
DOM10 www.corewebprogramming.com
DOM Installation and Setup
(continued)
4. Bookmark the DOM Level 2 and JAXP APIs
– DOM Level 2
• http://www.w3.org/TR/DOM-Level-2-Core/
– JAXP
• http://java.sun.com/xml/jaxp/dist/1.1/
docs/api/index.html
DOM11 www.corewebprogramming.com
Steps for DOM Parsing
1. Tell the system which parser you want to
use
2. Create a JAXP document builder
3. Invoke the parser to create a Document
representing an XML document
4. Normalize the tree
5. Obtain the root node of the tree
6. Examine and modify properties of the node
DOM12 www.corewebprogramming.com
Step 1: Specifying a Parser
• Approaches to specify a parser
– Set a system property for
javax.xml.parsers.DocumentBuilder-
Factory
– Specify the parser in
jre_dir/lib/jaxp.properties
– Through the J2EE Services API and the class specified
in META-INF/services/
javax.xml.parsers. DocumentBuilder-
Factory
– Use system-dependant default parser (check
documentation)
DOM13 www.corewebprogramming.com
Specifying a Parser, Example
• The following example:
– Permits the user to specify the parser through the
command line –D option
java –Djavax.xml.parser.DocumentBuilderFactory =
com.sun.xml.parser.DocumentBuilderFactoryImpl ...
– Uses the Apache Xerces parser otherwise
public static void main(String[] args) {
String jaxpPropertyName =
"javax.xml.parsers.DocumentBuilderFactory";
if (System.getProperty(jaxpPropertyName) == null) {
String apacheXercesPropertyValue =
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl";
System.setProperty(jaxpPropertyName,
apacheXercesPropertyValue);
}
...
}
DOM14 www.corewebprogramming.com
Step 2: Create a JAXP
Document Builder
• First create an instance of a builder factory,
then use that to create a DocumentBuilder
object
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
builderFactory.newDocumentBuilder();
– A builder is basically a wrapper around a specific XML
parser
– To set up namespace awareness and validation, use
builderFactory.setNamespaceAware(true)
builderFactory.setValidating(true)
DOM15 www.corewebprogramming.com
Step3: Invoke the Parser to
Create a Document
• Call the parse method of the
DocumentBuilder, supplying an XML
document (input stream)
Document document = builder.parse(someInputStream);
– The Document class represents the parsed result in a
tree structure
– The XML document can be represented as a:
• URI, represented as a string
• InputStream
• org.xml.sax.InputSource
DOM16 www.corewebprogramming.com
Step 4: Normalize the Tree
• Normalization has two affects:
– Combines textual nodes that span multiple lines
– Eliminates empty textual nodes
document.getDocumentElement().normalize();
DOM17 www.corewebprogramming.com
Step 5: Obtain the Root Node
of the Tree
• Traversing and modifying the tree begins at
the root node
Element rootElement = document.getDocumentElement();
– An Element is a subclass of the more general Node
class and represents an XML element
– A Node represents all the various components of an
XML document
• Document, Element, Attribute, Entity, Text, CDATA,
Processing Instruction, Comment, etc.
DOM18 www.corewebprogramming.com
Step 6: Examine and Modify
Properties of the Node
• Examine the various node properties
– getNodeName
• Returns the name of the element
– getNodeType
• Returns the node type
• Compare to Node constants
–DOCUMENT_NODE, ELEMENT_NODE, etc.
– getAttributes
• Returns a NamedNodeMap (collection of nodes, each
representing an attribute)
– Obtain particular attribute node through
getNamedItem
– getChildNodes
• Returns a NodeList collection of all the children
DOM19 www.corewebprogramming.com
Step 6: Examine and Modify
Properties of the Node (cont)
• Modify the document
– setNodeValue
• Assigns the text value of the node
– appendChild
• Adds a new node to the list of children
– removeChild
• Removes the child node from the list of children
– replaceChild
• Replace a child with a new node
DOM20 www.corewebprogramming.com
DOM Example: Representing an
XML Document as a JTree
• Approach
– Each XML document element is represented as a tree
node (in the JTree)
– Each tree node is either the element name or the
element name followed by a list of attributes
DOM21 www.corewebprogramming.com
DOM Example: Representing an
XML Document as a JTree
• Approach (cont.)
– The following steps are performed:
1. Parse and normalize the XML document and then
obtain the root node
2. Turn the root note into a JTree node
• The element name (getNodeName) is used for
the tree node label
• If attributes are present
(node.getAttributes), then include them in
the label enclosed in parentheses
3. Look up child elements (getChildNodes) and turn
them into JTree nodes, linking to their parent tree
node
4. Recursively apply step 3 to all child nodes
DOM22 www.corewebprogramming.com
DOM Example: XMLTree
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
/** Given a filename or a name and an input stream,
* this class generates a JTree representing the
* XML structure contained in the file or stream.
* Parses with DOM then copies the tree structure
* (minus text and comment nodes).
*/
public class XMLTree extends JTree {
public XMLTree(String filename) throws IOException {
this(filename, new FileInputStream(new File(filename)));
}
public XMLTree(String filename, InputStream in) {
super(makeRootNode(in));
}
DOM23 www.corewebprogramming.com
DOM Example: XMLTree
(continued)
private static DefaultMutableTreeNode
makeRootNode(InputStream in) {
try {
// Use the system property
// javax.xml.parsers.DocumentBuilderFactory (set either
// from Java code or by using the -D option to "java").
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
builderFactory.newDocumentBuilder();
Document document = builder.parse(in);
document.getDocumentElement().normalize();
Element rootElement = document.getDocumentElement();
DefaultMutableTreeNode rootTreeNode =
buildTree(rootElement);
return(rootTreeNode);
} catch(Exception e) {
String errorMessage = "Error making root node: " + e;
System.err.println(errorMessage);
e.printStackTrace();
return(new DefaultMutableTreeNode(errorMessage));
}
}
DOM24 www.corewebprogramming.com
DOM Example: XMLTree
(continued)
...
private static DefaultMutableTreeNode
buildTree(Element rootElement) {
// Make a JTree node for the root, then make JTree
// nodes for each child and add them to the root node.
// The addChildren method is recursive.
DefaultMutableTreeNode rootTreeNode =
new DefaultMutableTreeNode(treeNodeLabel(rootElement));
addChildren(rootTreeNode, rootElement);
return(rootTreeNode);
}
...
DOM25 www.corewebprogramming.com
DOM Example: XMLTree
(continued)
private static void addChildren
(DefaultMutableTreeNode parentTreeNode, Node parentXMLElement) {
// Recursive method that finds all the child elements and adds
// them to the parent node. Nodes corresponding to the graphical
// JTree will have the word "tree" in the variable name.
NodeList childElements =
parentXMLElement.getChildNodes();
for(int i=0; i<childElements.getLength(); i++) {
Node childElement = childElements.item(i);
if (!(childElement instanceof Text ||
childElement instanceof Comment)) {
DefaultMutableTreeNode childTreeNode =
new DefaultMutableTreeNode
(treeNodeLabel(childElement));
parentTreeNode.add(childTreeNode);
addChildren(childTreeNode, childElement);
}
}
}
DOM26 www.corewebprogramming.com
DOM Example: XMLTree
(continued)
...
private static String treeNodeLabel(Node childElement) {
NamedNodeMap elementAttributes =
childElement.getAttributes();
String treeNodeLabel = childElement.getNodeName();
if (elementAttributes != null &&
elementAttributes.getLength() > 0) {
treeNodeLabel = treeNodeLabel + " (";
int numAttributes = elementAttributes.getLength();
for(int i=0; i<numAttributes; i++) {
Node attribute = elementAttributes.item(i);
if (i > 0) {
treeNodeLabel = treeNodeLabel + ", ";
}
treeNodeLabel =
treeNodeLabel + attribute.getNodeName() +
"=" + attribute.getNodeValue();
}
treeNodeLabel = treeNodeLabel + ")";
}
return(treeNodeLabel);
}
}
DOM27 www.corewebprogramming.com
DOM Example: XMLFrame
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class XMLFrame extends JFrame {
public static void main(String[] args) {
String jaxpPropertyName =
"javax.xml.parsers.DocumentBuilderFactory";
// Pass the parser factory in on the command line with
// -D to override the use of the Apache parser.
if (System.getProperty(jaxpPropertyName) == null) {
String apacheXercesPropertyValue =
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl";
System.setProperty(jaxpPropertyName,
apacheXercesPropertyValue);
}
...
DOM28 www.corewebprogramming.com
DOM Example: XMLFrame
(continued)
String[] extensions = { "xml", "tld" };
WindowUtilities.setNativeLookAndFeel();
String filename = ExtensionFileFilter.getFileName(".",
"XML Files", extensions);
new XMLFrame(filename);
}
public XMLFrame(String filename) {
try {
WindowUtilities.setNativeLookAndFeel();
JTree tree = new XMLTree(filename);
JFrame frame = new JFrame(filename);
frame.addWindowListener(new ExitListener());
Container content = frame.getContentPane();
content.add(new JScrollPane(tree));
frame.pack();
frame.setVisible(true);
} catch(IOException ioe) {
System.out.println("Error creating tree: " + ioe);
}
}
}
DOM29 www.corewebprogramming.com
DOM Example: perennials.xml
<?xml version="1.0"?>
<!DOCTYPE perennials SYSTEM "dtds/perennials.dtd">
<perennials>
<daylily status="in-stock">
<cultivar>Luxury Lace</cultivar>
<award>
<name>Stout Medal</name>
<year>1965</year>
</award>
<award>
<name note="small-flowered">Annie T. Giles</name>
<year>1965</year>
</award>
<award>
<name>Lenington All-American</name>
<year>1970</year>
</award>
<bloom code="M">Midseason</bloom>
<cost discount="3" currency="US">11.75</cost>
</daylily>
...
<perennials>
DOM30 www.corewebprogramming.com
DOM Example: Results
DOM31 www.corewebprogramming.com
DOM Example: Results
(continued)
DOM32 www.corewebprogramming.com
DOM or SAX?
• DOM
– Suitable for small documents
– Easily modify document
– Memory intensive; load the complete XML document
• SAX
– Suitable for large documents; saves significant amounts
of memory
– Only traverse document once, start to end
– Event driven
– Limited standard functions
DOM33 www.corewebprogramming.com
Summary
• DOM is a tree representation of an XML
document in memory
– DOM provides a robust API to easily modify and extract
data from an XML document
• JAXP provides a vendor-neutral interface to
the underlying DOM or SAX parser
• Every component of the XML document is
represent as a Node
• Use normalization to combine text elements
spanning multiple lines
34 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?

More Related Content

What's hot

2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the ContextRussell Castagnaro
 
LDAP Integration
LDAP IntegrationLDAP Integration
LDAP IntegrationDell World
 
BGOUG 2012 - XML Index Strategies
BGOUG 2012 - XML Index StrategiesBGOUG 2012 - XML Index Strategies
BGOUG 2012 - XML Index StrategiesMarco Gralike
 
Hotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataHotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataMarco Gralike
 
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerUKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerMarco Gralike
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQLRaji Ghawi
 
Understanding Dom
Understanding DomUnderstanding Dom
Understanding DomLiquidHub
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued Hitesh-Java
 
aotc_120805_mwagner
aotc_120805_mwagneraotc_120805_mwagner
aotc_120805_mwagnerMary Wagner
 
LDAP - Lightweight Directory Access Protocol
LDAP - Lightweight Directory Access ProtocolLDAP - Lightweight Directory Access Protocol
LDAP - Lightweight Directory Access ProtocolS. Hasnain Raza
 
eXtensible Markup Language (XML)
eXtensible Markup Language (XML)eXtensible Markup Language (XML)
eXtensible Markup Language (XML)Serhii Kartashov
 
Everything you ever wanted to know about lotus script
Everything you ever wanted to know about lotus scriptEverything you ever wanted to know about lotus script
Everything you ever wanted to know about lotus scriptBill Buchan
 
Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDave Cross
 
LDAP Applied (EuroOSCON 2005)
LDAP Applied (EuroOSCON 2005)LDAP Applied (EuroOSCON 2005)
LDAP Applied (EuroOSCON 2005)Fran Fabrizio
 

What's hot (20)

2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the Context
 
Jndi (1)
Jndi (1)Jndi (1)
Jndi (1)
 
JAXB
JAXBJAXB
JAXB
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
 
LDAP Integration
LDAP IntegrationLDAP Integration
LDAP Integration
 
BGOUG 2012 - XML Index Strategies
BGOUG 2012 - XML Index StrategiesBGOUG 2012 - XML Index Strategies
BGOUG 2012 - XML Index Strategies
 
Hotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataHotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured Data
 
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerUKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQL
 
Understanding Dom
Understanding DomUnderstanding Dom
Understanding Dom
 
Ldap
LdapLdap
Ldap
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
 
aotc_120805_mwagner
aotc_120805_mwagneraotc_120805_mwagner
aotc_120805_mwagner
 
LDAP - Lightweight Directory Access Protocol
LDAP - Lightweight Directory Access ProtocolLDAP - Lightweight Directory Access Protocol
LDAP - Lightweight Directory Access Protocol
 
eXtensible Markup Language (XML)
eXtensible Markup Language (XML)eXtensible Markup Language (XML)
eXtensible Markup Language (XML)
 
Unit3wt
Unit3wtUnit3wt
Unit3wt
 
Everything you ever wanted to know about lotus script
Everything you ever wanted to know about lotus scriptEverything you ever wanted to know about lotus script
Everything you ever wanted to know about lotus script
 
XML SAX PARSING
XML SAX PARSING XML SAX PARSING
XML SAX PARSING
 
Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::Class
 
LDAP Applied (EuroOSCON 2005)
LDAP Applied (EuroOSCON 2005)LDAP Applied (EuroOSCON 2005)
LDAP Applied (EuroOSCON 2005)
 

Viewers also liked

Lucas customer service ch03
Lucas customer service ch03Lucas customer service ch03
Lucas customer service ch03EIBFS 2000
 
customer service ch01
customer service ch01customer service ch01
customer service ch01EIBFS 2000
 
Institutional reform for economic development icfs mafahem 12-2012 (1)
Institutional reform for economic development  icfs mafahem 12-2012 (1)Institutional reform for economic development  icfs mafahem 12-2012 (1)
Institutional reform for economic development icfs mafahem 12-2012 (1)Ossama El-Badawy
 
C# المحاضرة ال 8&9
C#  المحاضرة ال 8&9C#  المحاضرة ال 8&9
C# المحاضرة ال 8&9nermeenelhamy1
 
الرسالة والرؤية والقيم ـ الشخصية
الرسالة والرؤية والقيم ـ الشخصيةالرسالة والرؤية والقيم ـ الشخصية
الرسالة والرؤية والقيم ـ الشخصيةDr. Mubarak AlZanan
 
Customer Service Training
Customer Service TrainingCustomer Service Training
Customer Service TrainingKate Zabriskie
 
Internal Customer Service - Study Notes
Internal Customer Service - Study NotesInternal Customer Service - Study Notes
Internal Customer Service - Study NotesOxfordCambridge
 
External and Internal Customers
External and Internal Customers External and Internal Customers
External and Internal Customers Candece Mcalister
 
Managing customer service
Managing customer serviceManaging customer service
Managing customer serviceAldrin Bibon
 
ادارة المشاريع ببساطة
ادارة المشاريع ببساطةادارة المشاريع ببساطة
ادارة المشاريع ببساطةIsmail Ibrahim
 
True Health Fitness Power Point Presentation
True Health Fitness Power Point PresentationTrue Health Fitness Power Point Presentation
True Health Fitness Power Point Presentationjtardiff
 

Viewers also liked (20)

Lucas customer service ch03
Lucas customer service ch03Lucas customer service ch03
Lucas customer service ch03
 
customer service ch01
customer service ch01customer service ch01
customer service ch01
 
Economic
EconomicEconomic
Economic
 
Institutional reform for economic development icfs mafahem 12-2012 (1)
Institutional reform for economic development  icfs mafahem 12-2012 (1)Institutional reform for economic development  icfs mafahem 12-2012 (1)
Institutional reform for economic development icfs mafahem 12-2012 (1)
 
C# المحاضرة ال 8&9
C#  المحاضرة ال 8&9C#  المحاضرة ال 8&9
C# المحاضرة ال 8&9
 
الرسالة والرؤية والقيم ـ الشخصية
الرسالة والرؤية والقيم ـ الشخصيةالرسالة والرؤية والقيم ـ الشخصية
الرسالة والرؤية والقيم ـ الشخصية
 
Customer service online
Customer service onlineCustomer service online
Customer service online
 
Ch1 ar
Ch1 arCh1 ar
Ch1 ar
 
Customer Service Training
Customer Service TrainingCustomer Service Training
Customer Service Training
 
Ch.3 PowerPoint
Ch.3 PowerPointCh.3 PowerPoint
Ch.3 PowerPoint
 
Internal Customer Service - Study Notes
Internal Customer Service - Study NotesInternal Customer Service - Study Notes
Internal Customer Service - Study Notes
 
Problem solving
Problem solvingProblem solving
Problem solving
 
Marketing plan
Marketing planMarketing plan
Marketing plan
 
Internal customers and team work
Internal customers and team workInternal customers and team work
Internal customers and team work
 
External and Internal Customers
External and Internal Customers External and Internal Customers
External and Internal Customers
 
Managing customer service
Managing customer serviceManaging customer service
Managing customer service
 
إدارة المشروعات الاحترافية PMP
إدارة المشروعات الاحترافية PMPإدارة المشروعات الاحترافية PMP
إدارة المشروعات الاحترافية PMP
 
Customer service course
Customer service courseCustomer service course
Customer service course
 
ادارة المشاريع ببساطة
ادارة المشاريع ببساطةادارة المشاريع ببساطة
ادارة المشاريع ببساطة
 
True Health Fitness Power Point Presentation
True Health Fitness Power Point PresentationTrue Health Fitness Power Point Presentation
True Health Fitness Power Point Presentation
 

Similar to 25dom

Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_javaardnetij
 
Building XML Based Applications
Building XML Based ApplicationsBuilding XML Based Applications
Building XML Based ApplicationsPrabu U
 
buildingxmlbasedapplications-180322042009.pptx
buildingxmlbasedapplications-180322042009.pptxbuildingxmlbasedapplications-180322042009.pptx
buildingxmlbasedapplications-180322042009.pptxNKannanCSE
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)BOSS Webtech
 
Approaches to document/report generation
Approaches to document/report generation Approaches to document/report generation
Approaches to document/report generation plutext
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 
DSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/ExportDSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/ExportDuraSpace
 
NiFi - First approach
NiFi - First approachNiFi - First approach
NiFi - First approachMickael Cassy
 

Similar to 25dom (20)

Unit 2
Unit 2 Unit 2
Unit 2
 
Ch23
Ch23Ch23
Ch23
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_java
 
Dom parser
Dom parserDom parser
Dom parser
 
Xml
XmlXml
Xml
 
23xml
23xml23xml
23xml
 
Dom
DomDom
Dom
 
Building XML Based Applications
Building XML Based ApplicationsBuilding XML Based Applications
Building XML Based Applications
 
Unit iv xml dom
Unit iv xml domUnit iv xml dom
Unit iv xml dom
 
buildingxmlbasedapplications-180322042009.pptx
buildingxmlbasedapplications-180322042009.pptxbuildingxmlbasedapplications-180322042009.pptx
buildingxmlbasedapplications-180322042009.pptx
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
 
Approaches to document/report generation
Approaches to document/report generation Approaches to document/report generation
Approaches to document/report generation
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
Understanding XML DOM
Understanding XML DOMUnderstanding XML DOM
Understanding XML DOM
 
DSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/ExportDSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/Export
 
NiFi - First approach
NiFi - First approachNiFi - First approach
NiFi - First approach
 
XML and XPath details
XML and XPath detailsXML and XPath details
XML and XPath details
 
Dom
Dom Dom
Dom
 
C# File IO Operations
C# File IO OperationsC# File IO Operations
C# File IO Operations
 
DOM-XML
DOM-XMLDOM-XML
DOM-XML
 

More from Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Digwc
DigwcDigwc
Digwc
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 

Recently uploaded

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

25dom

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Document Object Model DOM
  • 2. DOM2 www.corewebprogramming.com Agenda • Introduction to DOM • Java API for XML Parsing (JAXP) • Installation and setup • Steps for DOM parsing • Example – Representing an XML Document as a JTree • DOM or SAX?
  • 3. DOM3 www.corewebprogramming.com Document Object Model (DOM) • DOM supports navigating and modifying XML documents – Hierarchical tree representation of document • Tree follows standard API • Creating tree is vendor specific • DOM is a language-neutral specification – Bindings exists for Java, C++, CORBA, JavaScript • DOM Versions – DOM 1.0 (1998) – DOM 2.0 Core Specification (2000) – Official Website for DOM •http://www.w3c.org/DOM/
  • 4. DOM4 www.corewebprogramming.com DOM Tree Document Document Type Element Element Element Attribute Attribute Text Comment Text Text Text Element Attribute Entity Reference Text
  • 5. DOM5 www.corewebprogramming.com DOM Advantages and Disadvantages • Advantages – Robust API for the DOM tree – Relatively simple to modify the data structure and extract data • Disadvantages – Stores the entire document in memory – As DOM was written for any language, method naming conventions don’t follow standard Java programming conventions
  • 6. DOM6 www.corewebprogramming.com Java API for XML Parsing (JAXP) • JAXP provides a vendor-neutral interface to the underlying DOM or SAX parser javax.xml.parsers DocumentBuilderFactory DocumentBuilder SAXParserFactory SAXParser ParserConfigurationException FactoryConfigurationError
  • 7. DOM7 www.corewebprogramming.com DOM Installation and Setup (JDK 1.4) • All the necessary classes for DOM and JAXP are included with JDK 1.4 • See javax.xml.* packages • For DOM and JAXP with JDK 1.3 see following viewgraphs
  • 8. DOM8 www.corewebprogramming.com DOM Installation and Setup (JDK 1.3) 1. Download a DOM-compliant parser • Java-based DOM parsers at http://www.xml.com/pub/rg/Java_Parsers • Recommend Apache Xerces-J parser at http://xml.apache.org/xerces-j/ 2. Download the Java API for XML Processing (JAXP) • JAXP is a small layer on top of DOM which supports specifying parsers through system properties versus hard coded • See http://java.sun.com/xml/ • Note: Apache Xerces-J already incorporates JAXP
  • 9. DOM9 www.corewebprogramming.com DOM Installation and Setup (continued) 3. Set your CLASSPATH to include the DOM (and JAXP) classes set CLASSPATH=xerces_install_dirxerces.jar; %CLASSPATH% or setenv CLASSPATH xerces_install_dir/xerces.jar: $CLASSPATH • For servlets, place xerces.jar in the server’s lib directory • Note: Tomcat 4.0 is prebundled with xerces.jar • Xerces-J already incorporates JAXP • For other parsers you may need to add jaxp.jar to your classpath and servlet lib directory
  • 10. DOM10 www.corewebprogramming.com DOM Installation and Setup (continued) 4. Bookmark the DOM Level 2 and JAXP APIs – DOM Level 2 • http://www.w3.org/TR/DOM-Level-2-Core/ – JAXP • http://java.sun.com/xml/jaxp/dist/1.1/ docs/api/index.html
  • 11. DOM11 www.corewebprogramming.com Steps for DOM Parsing 1. Tell the system which parser you want to use 2. Create a JAXP document builder 3. Invoke the parser to create a Document representing an XML document 4. Normalize the tree 5. Obtain the root node of the tree 6. Examine and modify properties of the node
  • 12. DOM12 www.corewebprogramming.com Step 1: Specifying a Parser • Approaches to specify a parser – Set a system property for javax.xml.parsers.DocumentBuilder- Factory – Specify the parser in jre_dir/lib/jaxp.properties – Through the J2EE Services API and the class specified in META-INF/services/ javax.xml.parsers. DocumentBuilder- Factory – Use system-dependant default parser (check documentation)
  • 13. DOM13 www.corewebprogramming.com Specifying a Parser, Example • The following example: – Permits the user to specify the parser through the command line –D option java –Djavax.xml.parser.DocumentBuilderFactory = com.sun.xml.parser.DocumentBuilderFactoryImpl ... – Uses the Apache Xerces parser otherwise public static void main(String[] args) { String jaxpPropertyName = "javax.xml.parsers.DocumentBuilderFactory"; if (System.getProperty(jaxpPropertyName) == null) { String apacheXercesPropertyValue = "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"; System.setProperty(jaxpPropertyName, apacheXercesPropertyValue); } ... }
  • 14. DOM14 www.corewebprogramming.com Step 2: Create a JAXP Document Builder • First create an instance of a builder factory, then use that to create a DocumentBuilder object DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); – A builder is basically a wrapper around a specific XML parser – To set up namespace awareness and validation, use builderFactory.setNamespaceAware(true) builderFactory.setValidating(true)
  • 15. DOM15 www.corewebprogramming.com Step3: Invoke the Parser to Create a Document • Call the parse method of the DocumentBuilder, supplying an XML document (input stream) Document document = builder.parse(someInputStream); – The Document class represents the parsed result in a tree structure – The XML document can be represented as a: • URI, represented as a string • InputStream • org.xml.sax.InputSource
  • 16. DOM16 www.corewebprogramming.com Step 4: Normalize the Tree • Normalization has two affects: – Combines textual nodes that span multiple lines – Eliminates empty textual nodes document.getDocumentElement().normalize();
  • 17. DOM17 www.corewebprogramming.com Step 5: Obtain the Root Node of the Tree • Traversing and modifying the tree begins at the root node Element rootElement = document.getDocumentElement(); – An Element is a subclass of the more general Node class and represents an XML element – A Node represents all the various components of an XML document • Document, Element, Attribute, Entity, Text, CDATA, Processing Instruction, Comment, etc.
  • 18. DOM18 www.corewebprogramming.com Step 6: Examine and Modify Properties of the Node • Examine the various node properties – getNodeName • Returns the name of the element – getNodeType • Returns the node type • Compare to Node constants –DOCUMENT_NODE, ELEMENT_NODE, etc. – getAttributes • Returns a NamedNodeMap (collection of nodes, each representing an attribute) – Obtain particular attribute node through getNamedItem – getChildNodes • Returns a NodeList collection of all the children
  • 19. DOM19 www.corewebprogramming.com Step 6: Examine and Modify Properties of the Node (cont) • Modify the document – setNodeValue • Assigns the text value of the node – appendChild • Adds a new node to the list of children – removeChild • Removes the child node from the list of children – replaceChild • Replace a child with a new node
  • 20. DOM20 www.corewebprogramming.com DOM Example: Representing an XML Document as a JTree • Approach – Each XML document element is represented as a tree node (in the JTree) – Each tree node is either the element name or the element name followed by a list of attributes
  • 21. DOM21 www.corewebprogramming.com DOM Example: Representing an XML Document as a JTree • Approach (cont.) – The following steps are performed: 1. Parse and normalize the XML document and then obtain the root node 2. Turn the root note into a JTree node • The element name (getNodeName) is used for the tree node label • If attributes are present (node.getAttributes), then include them in the label enclosed in parentheses 3. Look up child elements (getChildNodes) and turn them into JTree nodes, linking to their parent tree node 4. Recursively apply step 3 to all child nodes
  • 22. DOM22 www.corewebprogramming.com DOM Example: XMLTree import java.awt.*; import javax.swing.*; import javax.swing.tree.*; import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; /** Given a filename or a name and an input stream, * this class generates a JTree representing the * XML structure contained in the file or stream. * Parses with DOM then copies the tree structure * (minus text and comment nodes). */ public class XMLTree extends JTree { public XMLTree(String filename) throws IOException { this(filename, new FileInputStream(new File(filename))); } public XMLTree(String filename, InputStream in) { super(makeRootNode(in)); }
  • 23. DOM23 www.corewebprogramming.com DOM Example: XMLTree (continued) private static DefaultMutableTreeNode makeRootNode(InputStream in) { try { // Use the system property // javax.xml.parsers.DocumentBuilderFactory (set either // from Java code or by using the -D option to "java"). DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(in); document.getDocumentElement().normalize(); Element rootElement = document.getDocumentElement(); DefaultMutableTreeNode rootTreeNode = buildTree(rootElement); return(rootTreeNode); } catch(Exception e) { String errorMessage = "Error making root node: " + e; System.err.println(errorMessage); e.printStackTrace(); return(new DefaultMutableTreeNode(errorMessage)); } }
  • 24. DOM24 www.corewebprogramming.com DOM Example: XMLTree (continued) ... private static DefaultMutableTreeNode buildTree(Element rootElement) { // Make a JTree node for the root, then make JTree // nodes for each child and add them to the root node. // The addChildren method is recursive. DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode(treeNodeLabel(rootElement)); addChildren(rootTreeNode, rootElement); return(rootTreeNode); } ...
  • 25. DOM25 www.corewebprogramming.com DOM Example: XMLTree (continued) private static void addChildren (DefaultMutableTreeNode parentTreeNode, Node parentXMLElement) { // Recursive method that finds all the child elements and adds // them to the parent node. Nodes corresponding to the graphical // JTree will have the word "tree" in the variable name. NodeList childElements = parentXMLElement.getChildNodes(); for(int i=0; i<childElements.getLength(); i++) { Node childElement = childElements.item(i); if (!(childElement instanceof Text || childElement instanceof Comment)) { DefaultMutableTreeNode childTreeNode = new DefaultMutableTreeNode (treeNodeLabel(childElement)); parentTreeNode.add(childTreeNode); addChildren(childTreeNode, childElement); } } }
  • 26. DOM26 www.corewebprogramming.com DOM Example: XMLTree (continued) ... private static String treeNodeLabel(Node childElement) { NamedNodeMap elementAttributes = childElement.getAttributes(); String treeNodeLabel = childElement.getNodeName(); if (elementAttributes != null && elementAttributes.getLength() > 0) { treeNodeLabel = treeNodeLabel + " ("; int numAttributes = elementAttributes.getLength(); for(int i=0; i<numAttributes; i++) { Node attribute = elementAttributes.item(i); if (i > 0) { treeNodeLabel = treeNodeLabel + ", "; } treeNodeLabel = treeNodeLabel + attribute.getNodeName() + "=" + attribute.getNodeValue(); } treeNodeLabel = treeNodeLabel + ")"; } return(treeNodeLabel); } }
  • 27. DOM27 www.corewebprogramming.com DOM Example: XMLFrame import java.awt.*; import javax.swing.*; import java.io.*; public class XMLFrame extends JFrame { public static void main(String[] args) { String jaxpPropertyName = "javax.xml.parsers.DocumentBuilderFactory"; // Pass the parser factory in on the command line with // -D to override the use of the Apache parser. if (System.getProperty(jaxpPropertyName) == null) { String apacheXercesPropertyValue = "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"; System.setProperty(jaxpPropertyName, apacheXercesPropertyValue); } ...
  • 28. DOM28 www.corewebprogramming.com DOM Example: XMLFrame (continued) String[] extensions = { "xml", "tld" }; WindowUtilities.setNativeLookAndFeel(); String filename = ExtensionFileFilter.getFileName(".", "XML Files", extensions); new XMLFrame(filename); } public XMLFrame(String filename) { try { WindowUtilities.setNativeLookAndFeel(); JTree tree = new XMLTree(filename); JFrame frame = new JFrame(filename); frame.addWindowListener(new ExitListener()); Container content = frame.getContentPane(); content.add(new JScrollPane(tree)); frame.pack(); frame.setVisible(true); } catch(IOException ioe) { System.out.println("Error creating tree: " + ioe); } } }
  • 29. DOM29 www.corewebprogramming.com DOM Example: perennials.xml <?xml version="1.0"?> <!DOCTYPE perennials SYSTEM "dtds/perennials.dtd"> <perennials> <daylily status="in-stock"> <cultivar>Luxury Lace</cultivar> <award> <name>Stout Medal</name> <year>1965</year> </award> <award> <name note="small-flowered">Annie T. Giles</name> <year>1965</year> </award> <award> <name>Lenington All-American</name> <year>1970</year> </award> <bloom code="M">Midseason</bloom> <cost discount="3" currency="US">11.75</cost> </daylily> ... <perennials>
  • 32. DOM32 www.corewebprogramming.com DOM or SAX? • DOM – Suitable for small documents – Easily modify document – Memory intensive; load the complete XML document • SAX – Suitable for large documents; saves significant amounts of memory – Only traverse document once, start to end – Event driven – Limited standard functions
  • 33. DOM33 www.corewebprogramming.com Summary • DOM is a tree representation of an XML document in memory – DOM provides a robust API to easily modify and extract data from an XML document • JAXP provides a vendor-neutral interface to the underlying DOM or SAX parser • Every component of the XML document is represent as a Node • Use normalization to combine text elements spanning multiple lines
  • 34. 34 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?