SlideShare ist ein Scribd-Unternehmen logo
1 von 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 ] );
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
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 minutesVMware Tanzu
 
Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_colorDATAVERSITY
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
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!Oliver Gierke
 
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 WPNguyen Tuan
 
Tool Development 04 - XML
Tool Development 04 - XMLTool Development 04 - XML
Tool Development 04 - XMLNick Pruehs
 
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, YAMLNick Pruehs
 
Xml Presentation-1
Xml Presentation-1Xml Presentation-1
Xml Presentation-1Sudharsan S
 

Was ist angesagt? (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
 

Andere mochten auch

Semantic web xml-rdf-dom parser
Semantic web xml-rdf-dom parserSemantic web xml-rdf-dom parser
Semantic web xml-rdf-dom parserSerdar Sönmez
 
Java Web Service - Summer 2004
Java Web Service - Summer 2004Java Web Service - Summer 2004
Java Web Service - Summer 2004Danny Teng
 
Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108nit Allahabad
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XMLguest2556de
 
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 SOAPIMC Institute
 
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-RSIMC Institute
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)BOSS Webtech
 
Xml Java
Xml JavaXml Java
Xml Javacbee48
 
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 UDDIIMC Institute
 
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 ServicesIMC Institute
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7Lukáš Fryč
 

Andere mochten auch (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
 

Ähnlich wie java API for XML DOM

04 sm3 xml_xp_07
04 sm3 xml_xp_0704 sm3 xml_xp_07
04 sm3 xml_xp_07Niit Care
 
Xml And JSON Java
Xml And JSON JavaXml And JSON Java
Xml And JSON JavaHenry Addo
 
06 xml processing-in-.net
06 xml processing-in-.net06 xml processing-in-.net
06 xml processing-in-.netglubox
 
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 XMLMohammad Shaker
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_javaardnetij
 
Ado.net session13
Ado.net session13Ado.net session13
Ado.net session13Niit Care
 
Url&doc html
Url&doc htmlUrl&doc html
Url&doc htmlakila m
 
Creating A Language Editor Using Dltk
Creating A Language Editor Using DltkCreating A Language Editor Using Dltk
Creating A Language Editor Using DltkKaniska Mandal
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Nuxeo
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 

Ähnlich wie 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
 

Mehr von Surinder Kaur

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

Kürzlich hochgeladen

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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 2024Rafal Los
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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 Processorsdebabhi2
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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.pdfUK Journal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Kürzlich hochgeladen (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

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