SlideShare une entreprise Scribd logo
1  sur  34
JAVA API FOR XML DOM
Introduction
 Java WSDP: Java Web Services Developer
Pack
 Document-oriented Java API are:
– Java API for XML Processing (JAXP)
processes XML documents using various parsers
– Java Architecture for XML Binding (JAXB)
processes XML documents using schema-derived
JavaBeans component classes
DOM Classes and Interfaces
Class/Interface Description
Document interface Represents the XML document’s top-level
node, which provides access to all the document’s
nodes—including the root element.
Node interface Represents an XML document node.
NodeList interface Represents a read-only list of Node objects.
Element interface Represents an element node. Derives from
Node.
Attr interface Represents an attribute node. Derives from
Node.
CharacterData interface Represents character data. Derives from Node.
Text interface Represents a text node. Derives from
CharacterData.
DOM API of JAXP
Package Description
org.w3c.dom Defines the DOM programming interfaces
for XML documents, as specified by the
W3C.
javax.xml.parsers Provides classes related to parsing an XML
document.
DocumentBuilderFactory class and the
DocumentBuilder class,returns an object
that implements the W3C Document
interface.
This package also defines the
ParserConfigurationException class for
reporting errors.
Outline
XML
Doc.
Document
Builder
Document Builder
Factory
DOM
Simple DOM program, I
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class SecondDom {
public static void main(String args[]) {
try {
...Main part of program goes here...
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
Simple DOM program, II
 First we need to create a DOM parser, called a
―DocumentBuilder‖.
 Class DocumentBuilder provides a standard
interface to an XML parser.
 The parser is created, not by a constructor, but
by calling a static factory method
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
Simple DOM program, III
 The next step is to load in the XML file
 Here is the XML file, named hello.xml:
<?xml version="1.0"?>
<display>Hello World!</display>
 To read this file in, we add the following line to our
program:
Document document = builder.parse("hello.xml");
 Notes:
– document contains the entire XML file (as a tree); it is the
Document Object Model
– If you run this from the command line, your XML file should be in
the same directory as your program
Simple DOM program, IV
 The following code finds the content of the
root element and prints it:
Element root = document.getDocumentElement();
Node textNode = root.getFirstChild();
System.out.println(textNode.getNodeValue());
 The output of the program is: Hello World!
Reading in the tree
 The parse method reads in the entire XML
document and represents it as a tree in memory
 If parsing is successful, a Document object is
returned that contains nodes representing
each part of the intro.xml document.
– If you want to interact with your program while it is
parsing, you need to parse in a separate thread
» Once parsing starts, you cannot interrupt or stop it
» Do not try to access the parse tree until parsing is done
 An XML parse tree may require up to ten times
as much memory as the original XML document
Other required Packages
Package Description
com.sun.xml.tree contains classes and interfaces from
Sun Microsystem’s
internal XML API, which provides
features currently not available in the
XML 1.0 recommendation
org.xml.sax provides the Simple API for XML
programmatic interface.
A DOM-based parser may use an
event-based implementation (such as
Simple API for XML) to help create
the tree structure in memory.
intro.xml
<?xml version = "1.0"?>
<!-- Fig. 8.12 : intro.xml -->
<!-- Simple introduction to XML markup -->
<!DOCTYPE myMessage [
<!ELEMENT myMessage ( message )>
<!ELEMENT message ( #PCDATA )>
]>
<myMessage>
<message>Welcome to XML!</message>
</myMessage>
MODIFYING XML
DOCUMENT WITH DOM
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import com.sun.xml.tree.XmlDocument;
import org.xml.sax.*;
public class ReplaceText {
private Document document;
public ReplaceText() {
try {
// obtain the default parser
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// set the parser to validating
factory.setValidating( true );
DocumentBuilder builder =
factory.newDocumentBuilder();
// set error handler for errors related to
parsing
builder.setErrorHandler
( new MyErrorHandler() );
// obtain document object from XML document
document = builder.parse(
new File( "intro.xml" ) );
// fetch the root node
Node root =
document.getDocumentElement();
if ( root.getNodeType() == Node.ELEMENT_NODE ) {
Element myMessageNode = ( Element ) root;
NodeList messageNodes =
myMessageNode.getElementsByTagName( "message" );
if ( messageNodes.getLength() != 0 ) {
//item() returns type Object and need casting
Node message = messageNodes.item( 0 );
// create a text node
Text newText =
document.createTextNode("New Message!!" );
Cast root node as element
(subclass), then get list of all
message elements
// get the old text node
Text oldText =
( Text )message.getChildNodes().item( 0 );
// replace the text
message.replaceChild( newText, oldText
}
}
//Write new XML document to intro1.xml
( (XmlDocument) document).write(
new FileOutputStream("intro1.xml" ) );
}
catch ( SAXParseException spe ) {
System.err.println( "Parse error: " +
spe.getMessage() );
System.exit( 1 );
}
catch ( SAXException se ) {
se.printStackTrace();
}
catch ( FileNotFoundException fne ) {
System.err.println( “XML File not found. " );
System.exit( 1 );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
public static void main( String args[] )
{
ReplaceText d = new ReplaceText();
}
}
Building an XML Document
with DOM
 Desired Output
<root>
<!--This is a simple contact list-->
<contact gender="F">
<FirstName>Sue</FirstName>
<LastName>Green</LastName>
</contact>
<?myInstruction action silent?>
<![CDATA[I can add <, >, and ?]]>
</root>
import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import com.sun.xml.tree.XmlDocument;
public class BuildXml {
private Document document;
public BuildXml() {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
try {
// get DocumentBuilder
DocumentBuilder builder =
factory.newDocumentBuilder();
// create root node
document = builder.newDocument();
}
catch ( ParserConfigurationException pce ) {
pce.printStackTrace();
}
Element root = document.createElement( "root" );
document.appendChild( root );
Comment simpleComment =document.createComment(
"This is a simple contact list" );
root.appendChild( simpleComment );
Node contactNode =
createContactNode( document );
root.appendChild( contactNode );
ProcessingInstruction pi =
document.createProcessingInstruction(
"myInstruction", "action silent" );
root.appendChild( pi );
CDATASection cdata =
document.createCDATASection(
"I can add <, >, and ?" );
root.appendChild( cdata );
try {
// write the XML document to a file
( (XmlDocument) document).write(
new FileOutputStream("myDocument.xml" ) );
}
catch ( IOException ioe ) {
ioe.printStackTrace();
}
}
public Node createContactNode( Document document ) {
Element firstName =
document.createElement( "FirstName" );
firstName.appendChild(
document.createTextNode( "Sue" ) );
Element lastName =
document.createElement( "LastName" );
lastName.appendChild(
document.createTextNode( "Green" ) );
Element contact =
document.createElement( "contact" );
Attr genderAttribute =
document.createAttribute( "gender" );
genderAttribute.setValue( "F" );
contact.setAttributeNode( genderAttribute );
contact.appendChild( firstName );
contact.appendChild( lastName );
return contact;
}
public static void main( String args[] )
{
BuildXml buildXml = new BuildXml();
}
}
Traversing the DOM
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import com.sun.xml.tree.XmlDocument;
public class TraverseDOM {
private Document document;
public TraverseDOM( String file ) {
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
factory.setValidating( true );
DocumentBuilder builder =
factory.newDocumentBuilder();
builder.setErrorHandler(
new MyErrorHandler() );
document = builder.parse( new File( file ) );
processNode( document );
}
catch ( SAXParseException spe ) {
System.err.println("Parse error: " +
spe.getMessage() );
System.exit( 1 );
}
catch ( SAXException se ) {
se.printStackTrace();
}
catch ( FileNotFoundException fne ) {
System.err.println( "File not found. " );
System.exit( 1 );
}
catch ( Exception e ) { e.printStackTrace();}
}
public void processNode( Node currentNode ){
switch ( currentNode.getNodeType() ) {
case Node.DOCUMENT_NODE:
Document doc = ( Document ) currentNode;
System.out.println(
Document node: " + doc.getNodeName() +
"nRoot element: " +
doc.getDocumentElement().getNodeName() );
processChildNodes( doc.getChildNodes() );
break;
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;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
Text text = ( Text ) currentNode;
if ( !text.getNodeValue().trim().equals( "" ) )
System.out.println( "tText: " +
text.getNodeValue() );
break;
}
}
public void processChildNodes( NodeList children )
{
if ( children.getLength() != 0 )
for ( int i=0;i<children.getLength();i++)
processNode(children.item(i) );
}
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 ] );
}
}

Contenu connexe

Tendances

Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_color
DATAVERSITY
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
Staples
 
Xml Presentation-1
Xml Presentation-1Xml Presentation-1
Xml Presentation-1
Sudharsan S
 

Tendances (19)

An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
IT6801-Service Oriented Architecture-Unit-2-notes
IT6801-Service Oriented Architecture-Unit-2-notesIT6801-Service Oriented Architecture-Unit-2-notes
IT6801-Service Oriented Architecture-Unit-2-notes
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_color
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Parsing XML Data
Parsing XML DataParsing XML Data
Parsing XML Data
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Xml
XmlXml
Xml
 
Xml processors
Xml processorsXml processors
Xml processors
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 
Tool Development 04 - XML
Tool Development 04 - XMLTool Development 04 - XML
Tool Development 04 - XML
 
Tool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAMLTool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAML
 
Xml Presentation-1
Xml Presentation-1Xml Presentation-1
Xml Presentation-1
 
XXE
XXEXXE
XXE
 

En vedette

Semantic web xml-rdf-dom parser
Semantic web xml-rdf-dom parserSemantic web xml-rdf-dom parser
Semantic web xml-rdf-dom parser
Serdar Sönmez
 
Xml Java
Xml JavaXml Java
Xml Java
cbee48
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7
Lukáš Fryč
 

En vedette (20)

6 xml parsing
6   xml parsing6   xml parsing
6 xml parsing
 
Session 5
Session 5Session 5
Session 5
 
Xml3
Xml3Xml3
Xml3
 
Semantic web xml-rdf-dom parser
Semantic web xml-rdf-dom parserSemantic web xml-rdf-dom parser
Semantic web xml-rdf-dom parser
 
Dino's DEV Project
Dino's DEV ProjectDino's DEV Project
Dino's DEV Project
 
Introduce to XML
Introduce to XMLIntroduce to XML
Introduce to XML
 
XML SAX PARSING
XML SAX PARSING XML SAX PARSING
XML SAX PARSING
 
5 xml parsing
5   xml parsing5   xml parsing
5 xml parsing
 
XML DOM
XML DOMXML DOM
XML DOM
 
Java Web Service - Summer 2004
Java Web Service - Summer 2004Java Web Service - Summer 2004
Java Web Service - Summer 2004
 
Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XML
 
Java Web Services [2/5]: Introduction to SOAP
Java Web Services [2/5]: Introduction to SOAPJava Web Services [2/5]: Introduction to SOAP
Java Web Services [2/5]: Introduction to SOAP
 
Java Web Services [5/5]: REST and JAX-RS
Java Web Services [5/5]: REST and JAX-RSJava Web Services [5/5]: REST and JAX-RS
Java Web Services [5/5]: REST and JAX-RS
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
 
Xml Java
Xml JavaXml Java
Xml Java
 
Java Web Services [3/5]: WSDL, WADL and UDDI
Java Web Services [3/5]: WSDL, WADL and UDDIJava Web Services [3/5]: WSDL, WADL and UDDI
Java Web Services [3/5]: WSDL, WADL and UDDI
 
Java Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesJava Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web Services
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 

Similaire à java API for XML DOM (20)

Dom
Dom Dom
Dom
 
Understanding XML DOM
Understanding XML DOMUnderstanding XML DOM
Understanding XML DOM
 
04 sm3 xml_xp_07
04 sm3 xml_xp_0704 sm3 xml_xp_07
04 sm3 xml_xp_07
 
Xml And JSON Java
Xml And JSON JavaXml And JSON Java
Xml And JSON Java
 
Xml session
Xml sessionXml session
Xml session
 
06 xml processing-in-.net
06 xml processing-in-.net06 xml processing-in-.net
06 xml processing-in-.net
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
Xml
XmlXml
Xml
 
Unit 2
Unit 2 Unit 2
Unit 2
 
Xml11
Xml11Xml11
Xml11
 
XML.ppt
XML.pptXML.ppt
XML.ppt
 
Ch23
Ch23Ch23
Ch23
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_java
 
Xml writers
Xml writersXml writers
Xml writers
 
Ado.net session13
Ado.net session13Ado.net session13
Ado.net session13
 
Url&doc html
Url&doc htmlUrl&doc html
Url&doc html
 
srgoc
srgocsrgoc
srgoc
 
Creating A Language Editor Using Dltk
Creating A Language Editor Using DltkCreating A Language Editor Using Dltk
Creating A Language Editor Using Dltk
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 

Plus de Surinder Kaur (11)

Lucene
LuceneLucene
Lucene
 
Agile
AgileAgile
Agile
 
MapReduce
MapReduceMapReduce
MapReduce
 
Apache Hive
Apache HiveApache Hive
Apache Hive
 
JSON Parsing
JSON ParsingJSON Parsing
JSON Parsing
 
Analysis of Emergency Evacuation of Building using PEPA
Analysis of Emergency Evacuation of Building using PEPAAnalysis of Emergency Evacuation of Building using PEPA
Analysis of Emergency Evacuation of Building using PEPA
 
Skype
SkypeSkype
Skype
 
NAT
NATNAT
NAT
 
XSLT
XSLTXSLT
XSLT
 
intelligent sensors and sensor networks
intelligent sensors and sensor networksintelligent sensors and sensor networks
intelligent sensors and sensor networks
 
MPI n OpenMP
MPI n OpenMPMPI n OpenMP
MPI n OpenMP
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

java API for XML DOM

  • 1. JAVA API FOR XML DOM
  • 2. Introduction  Java WSDP: Java Web Services Developer Pack  Document-oriented Java API are: – Java API for XML Processing (JAXP) processes XML documents using various parsers – Java Architecture for XML Binding (JAXB) processes XML documents using schema-derived JavaBeans component classes
  • 3. DOM Classes and Interfaces Class/Interface Description Document interface Represents the XML document’s top-level node, which provides access to all the document’s nodes—including the root element. Node interface Represents an XML document node. NodeList interface Represents a read-only list of Node objects. Element interface Represents an element node. Derives from Node. Attr interface Represents an attribute node. Derives from Node. CharacterData interface Represents character data. Derives from Node. Text interface Represents a text node. Derives from CharacterData.
  • 4. DOM API of JAXP Package Description org.w3c.dom Defines the DOM programming interfaces for XML documents, as specified by the W3C. javax.xml.parsers Provides classes related to parsing an XML document. DocumentBuilderFactory class and the DocumentBuilder class,returns an object that implements the W3C Document interface. This package also defines the ParserConfigurationException class for reporting errors.
  • 6. Simple DOM program, I import javax.xml.parsers.*; import org.w3c.dom.*; public class SecondDom { public static void main(String args[]) { try { ...Main part of program goes here... } catch (Exception e) { e.printStackTrace(System.out); } } }
  • 7. Simple DOM program, II  First we need to create a DOM parser, called a ―DocumentBuilder‖.  Class DocumentBuilder provides a standard interface to an XML parser.  The parser is created, not by a constructor, but by calling a static factory method DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder();
  • 8. Simple DOM program, III  The next step is to load in the XML file  Here is the XML file, named hello.xml: <?xml version="1.0"?> <display>Hello World!</display>  To read this file in, we add the following line to our program: Document document = builder.parse("hello.xml");  Notes: – document contains the entire XML file (as a tree); it is the Document Object Model – If you run this from the command line, your XML file should be in the same directory as your program
  • 9. Simple DOM program, IV  The following code finds the content of the root element and prints it: Element root = document.getDocumentElement(); Node textNode = root.getFirstChild(); System.out.println(textNode.getNodeValue());  The output of the program is: Hello World!
  • 10. Reading in the tree  The parse method reads in the entire XML document and represents it as a tree in memory  If parsing is successful, a Document object is returned that contains nodes representing each part of the intro.xml document. – If you want to interact with your program while it is parsing, you need to parse in a separate thread » Once parsing starts, you cannot interrupt or stop it » Do not try to access the parse tree until parsing is done  An XML parse tree may require up to ten times as much memory as the original XML document
  • 11. Other required Packages Package Description com.sun.xml.tree contains classes and interfaces from Sun Microsystem’s internal XML API, which provides features currently not available in the XML 1.0 recommendation org.xml.sax provides the Simple API for XML programmatic interface. A DOM-based parser may use an event-based implementation (such as Simple API for XML) to help create the tree structure in memory.
  • 12. intro.xml <?xml version = "1.0"?> <!-- Fig. 8.12 : intro.xml --> <!-- Simple introduction to XML markup --> <!DOCTYPE myMessage [ <!ELEMENT myMessage ( message )> <!ELEMENT message ( #PCDATA )> ]> <myMessage> <message>Welcome to XML!</message> </myMessage>
  • 14. import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; import com.sun.xml.tree.XmlDocument; import org.xml.sax.*; public class ReplaceText { private Document document; public ReplaceText() { try { // obtain the default parser DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // set the parser to validating factory.setValidating( true );
  • 15. DocumentBuilder builder = factory.newDocumentBuilder(); // set error handler for errors related to parsing builder.setErrorHandler ( new MyErrorHandler() ); // obtain document object from XML document document = builder.parse( new File( "intro.xml" ) ); // fetch the root node Node root = document.getDocumentElement();
  • 16. if ( root.getNodeType() == Node.ELEMENT_NODE ) { Element myMessageNode = ( Element ) root; NodeList messageNodes = myMessageNode.getElementsByTagName( "message" ); if ( messageNodes.getLength() != 0 ) { //item() returns type Object and need casting Node message = messageNodes.item( 0 ); // create a text node Text newText = document.createTextNode("New Message!!" ); Cast root node as element (subclass), then get list of all message elements
  • 17. // get the old text node Text oldText = ( Text )message.getChildNodes().item( 0 ); // replace the text message.replaceChild( newText, oldText } } //Write new XML document to intro1.xml ( (XmlDocument) document).write( new FileOutputStream("intro1.xml" ) ); }
  • 18. catch ( SAXParseException spe ) { System.err.println( "Parse error: " + spe.getMessage() ); System.exit( 1 ); } catch ( SAXException se ) { se.printStackTrace(); } catch ( FileNotFoundException fne ) { System.err.println( “XML File not found. " ); System.exit( 1 ); } catch ( Exception e ) { e.printStackTrace(); } }
  • 19. public static void main( String args[] ) { ReplaceText d = new ReplaceText(); } }
  • 20. Building an XML Document with DOM
  • 21.  Desired Output <root> <!--This is a simple contact list--> <contact gender="F"> <FirstName>Sue</FirstName> <LastName>Green</LastName> </contact> <?myInstruction action silent?> <![CDATA[I can add <, >, and ?]]> </root>
  • 22. import java.io.*; import org.w3c.dom.*; import org.xml.sax.*; import javax.xml.parsers.*; import com.sun.xml.tree.XmlDocument; public class BuildXml { private Document document; public BuildXml() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  • 23. try { // get DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // create root node document = builder.newDocument(); } catch ( ParserConfigurationException pce ) { pce.printStackTrace(); }
  • 24. Element root = document.createElement( "root" ); document.appendChild( root ); Comment simpleComment =document.createComment( "This is a simple contact list" ); root.appendChild( simpleComment ); Node contactNode = createContactNode( document ); root.appendChild( contactNode ); ProcessingInstruction pi = document.createProcessingInstruction( "myInstruction", "action silent" ); root.appendChild( pi ); CDATASection cdata = document.createCDATASection( "I can add <, >, and ?" ); root.appendChild( cdata );
  • 25. try { // write the XML document to a file ( (XmlDocument) document).write( new FileOutputStream("myDocument.xml" ) ); } catch ( IOException ioe ) { ioe.printStackTrace(); } }
  • 26. public Node createContactNode( Document document ) { Element firstName = document.createElement( "FirstName" ); firstName.appendChild( document.createTextNode( "Sue" ) ); Element lastName = document.createElement( "LastName" ); lastName.appendChild( document.createTextNode( "Green" ) ); Element contact = document.createElement( "contact" ); Attr genderAttribute = document.createAttribute( "gender" ); genderAttribute.setValue( "F" ); contact.setAttributeNode( genderAttribute ); contact.appendChild( firstName ); contact.appendChild( lastName ); return contact; }
  • 27. public static void main( String args[] ) { BuildXml buildXml = new BuildXml(); } }
  • 29. import org.w3c.dom.*; import org.xml.sax.*; import javax.xml.parsers.*; import com.sun.xml.tree.XmlDocument; public class TraverseDOM { private Document document; public TraverseDOM( String file ) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating( true ); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler( new MyErrorHandler() );
  • 30. document = builder.parse( new File( file ) ); processNode( document ); } catch ( SAXParseException spe ) { System.err.println("Parse error: " + spe.getMessage() ); System.exit( 1 ); } catch ( SAXException se ) { se.printStackTrace(); } catch ( FileNotFoundException fne ) { System.err.println( "File not found. " ); System.exit( 1 ); } catch ( Exception e ) { e.printStackTrace();} }
  • 31. public void processNode( Node currentNode ){ switch ( currentNode.getNodeType() ) { case Node.DOCUMENT_NODE: Document doc = ( Document ) currentNode; System.out.println( Document node: " + doc.getNodeName() + "nRoot element: " + doc.getDocumentElement().getNodeName() ); processChildNodes( doc.getChildNodes() ); break;
  • 32. 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;
  • 33. case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: Text text = ( Text ) currentNode; if ( !text.getNodeValue().trim().equals( "" ) ) System.out.println( "tText: " + text.getNodeValue() ); break; } } public void processChildNodes( NodeList children ) { if ( children.getLength() != 0 ) for ( int i=0;i<children.getLength();i++) processNode(children.item(i) ); }
  • 34. 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 ] ); } }