SlideShare une entreprise Scribd logo
1  sur  24
DOM & SAX
Roadmap ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What are XML APIs for? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Overview of JAXP ,[object Object],[object Object],[object Object],Defines the XSLT APIs that let you transform XML into other forms.  (Not covered today.) javax.xml.transform Defines the basic SAX APIs. org.xml.sax Defines the Document class (a DOM), as well as classes for all of the components of a DOM. org.w3c.dom The main JAXP APIs, which provide a common interface for various SAX and DOM parsers. javax.xml.parsers
JAXP XML Parsers ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
SAX vs. DOM ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],SAX = Simple API for XML DOM = Document Object Model There is also JDOM … more later
SAX Architecture
Using SAX ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],(This reflects SAX 1, which you can still use, but SAX 2 prefers a new incantation…) Here’s the standard recipe for starting with SAX:
Using SAX 2 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],But where does  myContentHandler  come from? In SAX 2, the following usage is preferred:
Defining a  ContentHandler ,[object Object],[object Object],[object Object],startDocument () // receive notice of start of document endDocument () // receive notice of end of document startElement () // receive notice of start of each element endElement () // receive notice of end of each element characters () // receive a chunk of character data error () // receive notice of recoverable parser error // ...plus more...
startElement() and  endElement() ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],startElement ( String  namespaceURI, // for use w/ namespaces   String  localName, // for use w/ namespaces   String  qName, // "qualified" name -- use this one!   Attributes  atts) endElement ( String  namespaceURI,   String  localName,   String  qName) The  SAXParser  invokes your callbacks to notify you of events:
SAX Attributes ,[object Object],[object Object],getLength ()  // return number of attributes getIndex ( String   qName ) // look up attribute's index by qName getValue ( String   qName ) // look up attribute's value by qName getValue ( int   index ) // look up attribute's value by index // ... and others ...
SAX  characters() ,[object Object],[object Object],public   void   characters ( char []   ch ,  // buffer containing chars   int   start ,   // start position in buffer   int   length )   // num of chars to read The  characters ()  event handler receives notification of character data (i.e. content that is not part of an XML element):
SAXExample : Input XML <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <dots> this is before the first dot and it continues on multiple lines <dot x=&quot;9&quot; y=&quot;81&quot; /> <dot x=&quot;11&quot; y=&quot;121&quot; /> <flip> flip is on <dot x=&quot;196&quot; y=&quot;14&quot; /> <dot x=&quot;169&quot; y=&quot;13&quot; /> </flip> flip is off <dot x=&quot;12&quot; y=&quot;144&quot; /> <extra> stuff </extra> <!-- a final comment --> </dots>
SAXExample : Code Please see  SAXExample.java
SAXExample : Input    Output startDocument startElement: dots (0 attributes) characters:  this is before the first dot and it continues on multiple lines startElement: dot (2 attributes) endElement:  dot startElement: dot (2 attributes) endElement:  dot startElement: flip (0 attributes) characters:  flip is on startElement: dot (2 attributes) endElement:  dot startElement: dot (2 attributes) endElement:  dot endElement:  flip characters:  flip is off startElement: dot (2 attributes) endElement:  dot startElement: extra (0 attributes) characters:  stuff endElement:  extra endElement:  dots endDocument Finished parsing input.  Got the following dots: [(9, 81), (11, 121), (14, 196), (13, 169), (12, 144)] <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <dots> this is before the first dot and it continues on multiple lines <dot x=&quot;9&quot; y=&quot;81&quot; /> <dot x=&quot;11&quot; y=&quot;121&quot; /> <flip> flip is on <dot x=&quot;196&quot; y=&quot;14&quot; /> <dot x=&quot;169&quot; y=&quot;13&quot; /> </flip> flip is off <dot x=&quot;12&quot; y=&quot;144&quot; /> <extra> stuff </extra> <!-- a final comment --> </dots>
DOM Architecture
DOM  Document  Structure Document +--- Element <dots> +--- Text &quot;this is before the first dot |   and it continues on multiple lines&quot; +--- Element <dot> +--- Text &quot;&quot; +--- Element <dot> +--- Text &quot;&quot; +--- Element <flip> |   +--- Text &quot;flip is on&quot; |   +--- Element <dot> |   +--- Text &quot;&quot; |   +--- Element <dot> |   +--- Text &quot;&quot; +--- Text &quot;flip is off&quot; +--- Element <dot> +--- Text &quot;&quot; +--- Element <extra> |   +--- Text &quot;stuff&quot; +--- Text &quot;&quot; +--- Comment &quot;a final comment&quot; +--- Text &quot;&quot; XML Input: Document  structure: ,[object Object],[object Object],[object Object],<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <dots> this is before the first dot and it continues on multiple lines <dot x=&quot;9&quot; y=&quot;81&quot; /> <dot x=&quot;11&quot; y=&quot;121&quot; /> <flip> flip is on <dot x=&quot;196&quot; y=&quot;14&quot; /> <dot x=&quot;169&quot; y=&quot;13&quot; /> </flip> flip is off <dot x=&quot;12&quot; y=&quot;144&quot; /> <extra> stuff </extra> <!-- a final comment --> </dots>
Using DOM import   javax.xml.parsers.* ; import   org.w3c.dom.* ; // get a DocumentBuilder object DocumentBuilderFactory   dbf  = DocumentBuilderFactory.newInstance(); DocumentBuilder   db  = null; try  { db = dbf.newDocumentBuilder(); }  catch  ( ParserConfigurationException   e ) { e.printStackTrace(); } // invoke parser to get a Document Document   doc  = db.parse(inputStream); Document   doc  = db.parse(file); Document   doc  = db.parse(url); Here’s the basic recipe for getting started with DOM:
DOM  Document  access idioms // get the root of the Document tree Element   root  = doc.getDocumentElement(); // get nodes in subtree by tag name NodeList   dots  = root.getElementsByTagName( &quot;dot&quot; ); // get first dot element Element   firstDot  = ( Element ) dots.item(0); // get x attribute of first dot String   x  = firstDot.getAttribute( &quot;x&quot; ); OK, say we have a  Document .  How do we get at the pieces of it? Here are some common idioms:
More  Document  accessors Node  access methods: String getNodeName () short getNodeType () Document getOwnerDocument () boolean hasChildNodes () NodeList getChildNodes () Node getFirstChild () Node getLastChild () Node getParentNode () Node getNextSibling () Node getPreviousSibling () boolean hasAttributes () ... and more ... Element  extends  Node  and adds these access methods: String getTagName () boolean hasAttribute ( String   name ) String getAttribute ( String   name ) NodeList getElementsByTagName ( String   name ) …  and more … Document  extends  Node  and adds these access methods: Element getDocumentElement () DocumentType getDoctype () ... plus the  Element  methods just mentioned ... ... and more ... e.g.  DOCUMENT_NODE ,  ELEMENT_NODE ,  TEXT_NODE ,  COMMENT_NODE , etc.
Creating & manipulating  Document s // get new empty Document from DocumentBuilder Document   doc  = db.newDocument(); // create a new <dots> Element and add to Document as root Element   root  = doc.createElement( &quot;dots&quot; ); doc.appendChild(root); // create a new <dot> Element and add as child of root Element   dot  = doc.createElement( &quot;dot&quot; ); dot.setAttribute( &quot;x&quot; ,  &quot;9&quot; ); dot.setAttribute( &quot;y&quot; ,  &quot;81&quot; ); root.appendChild(dot); The DOM API also includes lots of methods for creating and manipulating  Document  objects:
More  Document  manipulators Node  manipulation methods: void setNodeValue ( String   nodeValue ) Node appendChild ( Node   newChild ) Node insertBefore ( Node   newChild ,  Node   refChild ) Node removeChild ( Node   oldChild ) ... and more ... Element  manipulation methods: void setAttribute ( String   name ,  String   value ) void removeAttribute ( String   name ) …  and more … Document  manipulation methods: Text createTextNode ( String   data ) Comment createCommentNode ( String   data ) ... and more ...
Writing a  Document  as XML ,[object Object],[object Object],[object Object],[object Object],[object Object],import   org.apache.crimson.tree.XmlDocument ; XmlDocument   x  = ( XmlDocument ) doc; x.write(out,  &quot;UTF-8&quot; );

Contenu connexe

Tendances

PhD Presentation
PhD PresentationPhD Presentation
PhD Presentation
mskayed
 

Tendances (20)

Dom parser
Dom parserDom parser
Dom parser
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Python xml processing
Python   xml processingPython   xml processing
Python xml processing
 
Unit3wt
Unit3wtUnit3wt
Unit3wt
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
 
PhD Presentation
PhD PresentationPhD Presentation
PhD Presentation
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
Pxb For Yapc2008
Pxb For Yapc2008Pxb For Yapc2008
Pxb For Yapc2008
 
Pollock
PollockPollock
Pollock
 
Learning XSLT
Learning XSLTLearning XSLT
Learning XSLT
 
Xslt by asfak mahamud
Xslt by asfak mahamudXslt by asfak mahamud
Xslt by asfak mahamud
 
Transforming xml with XSLT
Transforming  xml with XSLTTransforming  xml with XSLT
Transforming xml with XSLT
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming Language
 
Json - ideal for data interchange
Json - ideal for data interchangeJson - ideal for data interchange
Json - ideal for data interchange
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
SQL - RDBMS Concepts
SQL - RDBMS ConceptsSQL - RDBMS Concepts
SQL - RDBMS Concepts
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
 
XML Tools for Perl
XML Tools for PerlXML Tools for Perl
XML Tools for Perl
 
Apache Avro in LivePerson [Hebrew]
Apache Avro in LivePerson [Hebrew]Apache Avro in LivePerson [Hebrew]
Apache Avro in LivePerson [Hebrew]
 
XML for beginners
XML for beginnersXML for beginners
XML for beginners
 

Similaire à Sax Dom Tutorial

IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic CommunicationIQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
Ted Leung
 
Xml Java
Xml JavaXml Java
Xml Java
cbee48
 

Similaire à Sax Dom Tutorial (20)

Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
 
5 xml parsing
5   xml parsing5   xml parsing
5 xml parsing
 
JAXP
JAXPJAXP
JAXP
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Inroduction to XSLT with PHP4
Inroduction to XSLT with PHP4Inroduction to XSLT with PHP4
Inroduction to XSLT with PHP4
 
XML and Web Services with PHP5 and PEAR
XML and Web Services with PHP5 and PEARXML and Web Services with PHP5 and PEAR
XML and Web Services with PHP5 and PEAR
 
Mazda Use of Third Generation Xml Tools
Mazda Use of Third Generation Xml ToolsMazda Use of Third Generation Xml Tools
Mazda Use of Third Generation Xml Tools
 
Xml
XmlXml
Xml
 
Stax parser
Stax parserStax parser
Stax parser
 
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic CommunicationIQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
 
XML
XMLXML
XML
 
Xml Java
Xml JavaXml Java
Xml Java
 
6 311 W
6 311 W6 311 W
6 311 W
 
6 311 W
6 311 W6 311 W
6 311 W
 
test
testtest
test
 
XML Transformations With PHP
XML Transformations With PHPXML Transformations With PHP
XML Transformations With PHP
 
Developing web apps using Erlang-Web
Developing web apps using Erlang-WebDeveloping web apps using Erlang-Web
Developing web apps using Erlang-Web
 
XPath - XML Path Language
XPath - XML Path LanguageXPath - XML Path Language
XPath - XML Path Language
 
Javascript2839
Javascript2839Javascript2839
Javascript2839
 
Json
JsonJson
Json
 

Plus de vikram singh

Plus de vikram singh (20)

Agile
AgileAgile
Agile
 
Enterprise java beans(ejb) Update 2
Enterprise java beans(ejb) Update 2Enterprise java beans(ejb) Update 2
Enterprise java beans(ejb) Update 2
 
Web tech importants
Web tech importantsWeb tech importants
Web tech importants
 
Enterprise Java Beans( E)
Enterprise  Java  Beans( E)Enterprise  Java  Beans( E)
Enterprise Java Beans( E)
 
Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2
 
Enterprise java beans(ejb)
Enterprise java beans(ejb)Enterprise java beans(ejb)
Enterprise java beans(ejb)
 
2 4 Tree
2 4 Tree2 4 Tree
2 4 Tree
 
23 Tree Best Part
23 Tree   Best Part23 Tree   Best Part
23 Tree Best Part
 
JSP Scope variable And Data Sharing
JSP Scope variable And Data SharingJSP Scope variable And Data Sharing
JSP Scope variable And Data Sharing
 
Bean Intro
Bean IntroBean Intro
Bean Intro
 
jdbc
jdbcjdbc
jdbc
 
Xml
XmlXml
Xml
 
Dtd
DtdDtd
Dtd
 
Xml Schema
Xml SchemaXml Schema
Xml Schema
 
JSP
JSPJSP
JSP
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
 
Servlet Part 2
Servlet Part 2Servlet Part 2
Servlet Part 2
 
Tutorial Solution
Tutorial SolutionTutorial Solution
Tutorial Solution
 
Java Script Language Tutorial
Java Script Language TutorialJava Script Language Tutorial
Java Script Language Tutorial
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Dernier (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Sax Dom Tutorial

  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14. SAXExample : Input XML <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <dots> this is before the first dot and it continues on multiple lines <dot x=&quot;9&quot; y=&quot;81&quot; /> <dot x=&quot;11&quot; y=&quot;121&quot; /> <flip> flip is on <dot x=&quot;196&quot; y=&quot;14&quot; /> <dot x=&quot;169&quot; y=&quot;13&quot; /> </flip> flip is off <dot x=&quot;12&quot; y=&quot;144&quot; /> <extra> stuff </extra> <!-- a final comment --> </dots>
  • 15. SAXExample : Code Please see SAXExample.java
  • 16. SAXExample : Input  Output startDocument startElement: dots (0 attributes) characters: this is before the first dot and it continues on multiple lines startElement: dot (2 attributes) endElement: dot startElement: dot (2 attributes) endElement: dot startElement: flip (0 attributes) characters: flip is on startElement: dot (2 attributes) endElement: dot startElement: dot (2 attributes) endElement: dot endElement: flip characters: flip is off startElement: dot (2 attributes) endElement: dot startElement: extra (0 attributes) characters: stuff endElement: extra endElement: dots endDocument Finished parsing input. Got the following dots: [(9, 81), (11, 121), (14, 196), (13, 169), (12, 144)] <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <dots> this is before the first dot and it continues on multiple lines <dot x=&quot;9&quot; y=&quot;81&quot; /> <dot x=&quot;11&quot; y=&quot;121&quot; /> <flip> flip is on <dot x=&quot;196&quot; y=&quot;14&quot; /> <dot x=&quot;169&quot; y=&quot;13&quot; /> </flip> flip is off <dot x=&quot;12&quot; y=&quot;144&quot; /> <extra> stuff </extra> <!-- a final comment --> </dots>
  • 18.
  • 19. Using DOM import javax.xml.parsers.* ; import org.w3c.dom.* ; // get a DocumentBuilder object DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch ( ParserConfigurationException e ) { e.printStackTrace(); } // invoke parser to get a Document Document doc = db.parse(inputStream); Document doc = db.parse(file); Document doc = db.parse(url); Here’s the basic recipe for getting started with DOM:
  • 20. DOM Document access idioms // get the root of the Document tree Element root = doc.getDocumentElement(); // get nodes in subtree by tag name NodeList dots = root.getElementsByTagName( &quot;dot&quot; ); // get first dot element Element firstDot = ( Element ) dots.item(0); // get x attribute of first dot String x = firstDot.getAttribute( &quot;x&quot; ); OK, say we have a Document . How do we get at the pieces of it? Here are some common idioms:
  • 21. More Document accessors Node access methods: String getNodeName () short getNodeType () Document getOwnerDocument () boolean hasChildNodes () NodeList getChildNodes () Node getFirstChild () Node getLastChild () Node getParentNode () Node getNextSibling () Node getPreviousSibling () boolean hasAttributes () ... and more ... Element extends Node and adds these access methods: String getTagName () boolean hasAttribute ( String name ) String getAttribute ( String name ) NodeList getElementsByTagName ( String name ) … and more … Document extends Node and adds these access methods: Element getDocumentElement () DocumentType getDoctype () ... plus the Element methods just mentioned ... ... and more ... e.g. DOCUMENT_NODE , ELEMENT_NODE , TEXT_NODE , COMMENT_NODE , etc.
  • 22. Creating & manipulating Document s // get new empty Document from DocumentBuilder Document doc = db.newDocument(); // create a new <dots> Element and add to Document as root Element root = doc.createElement( &quot;dots&quot; ); doc.appendChild(root); // create a new <dot> Element and add as child of root Element dot = doc.createElement( &quot;dot&quot; ); dot.setAttribute( &quot;x&quot; , &quot;9&quot; ); dot.setAttribute( &quot;y&quot; , &quot;81&quot; ); root.appendChild(dot); The DOM API also includes lots of methods for creating and manipulating Document objects:
  • 23. More Document manipulators Node manipulation methods: void setNodeValue ( String nodeValue ) Node appendChild ( Node newChild ) Node insertBefore ( Node newChild , Node refChild ) Node removeChild ( Node oldChild ) ... and more ... Element manipulation methods: void setAttribute ( String name , String value ) void removeAttribute ( String name ) … and more … Document manipulation methods: Text createTextNode ( String data ) Comment createCommentNode ( String data ) ... and more ...
  • 24.