SlideShare uma empresa Scribd logo
1 de 65
Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers www.devbg.org
Contents ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
XML Parsers
XML Parsers ,[object Object],[object Object],[object Object],[object Object],[object Object]
XML Parsers – Models ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using a XML Parser ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Types of Parser ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The DOM Parser
DOM Parser Architecture
DOM Key Features ,[object Object],[object Object],[object Object],[object Object],[object Object]
The DOM   Parser – Example  ,[object Object],<?xml version=&quot;1.0&quot;?> <library name=&quot;.NET Developer's Library&quot;> <book> <title>Programming Microsoft .NET</title> <author>Jeff Prosise</author> <isbn>0-7356-1376-1</isbn> </book> <book> <title>Microsoft   .NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1-930110-19-7</isbn > </book> </library>
The DOM   Parser – Example ,[object Object],Header part Root node
The SAX Parser
SAX Key Features ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The SAX Parser ,[object Object],[object Object],[object Object]
The StAX Parser ,[object Object],[object Object],[object Object],[object Object],[object Object]
When to Use   DOM   and When to Use SAX/StAX? ,[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],When to Use   DOM   and When to Use SAX/StAX?
Introduction to  JAXP
JAXP ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JAXP – Plugability ,[object Object],[object Object],[object Object],[object Object],[object Object]
JAXP – Independence ,[object Object],[object Object],[object Object]
JAXP Packages ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JAXP Packages (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using the DOM Parser
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: <?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  Document  Structure ,[object Object],[object Object],[object Object],[object Object]
DOM Classes Hierarchy
Using DOM import javax.xml.parsers.*; import org.w3c.dom.*; //  G et a DocumentBuilder object DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } //  I nvoke 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:
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;); ,[object Object],[object Object]
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 ... e.g. DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE, COMMENT_NODE, etc.
More  Document  Accessors 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 ...
Writing a  Document  as XML ,[object Object],[object Object],[object Object],import com.sun.org.apache.xml.internal. serialize.XMLSerializer; XMLSerializer xmlser = new XMLSerializer(); xmlser.setOutputByteStream(System.out); xmlser.serialize(doc);
Reading and Parsing XML Documents with the DOM Parser Live Demo
Creating & Manipulating DOM Documents // Get new empty Document from DocumentBuilder Document doc = docBuilder.newDocument(); // Create a new <dots> element // and add it to the document as root Element root = doc.createElement(&quot;dots&quot;); doc.appendChild(root); // Create a new <dot> element // and add as child of the 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); ,[object Object]
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 ...
Building Documents with the DOM Parser Live Demo
Using The StAX Parser
The StAX Parser in Java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Parsing Documents with the StAX Parser – Example FileReader fileReader = new FileReader(&quot;Student.xml&quot;); XMLInputFactory factory = XMLInputFactory. newInstance (); XMLStreamReader reader = factory.createXMLStreamReader(fileReader); String element = &quot;&quot;; while (reader.hasNext()) { if (reader.isStartElement()) { element = reader.getLocalName(); } else if (reader.isCharacters() &&        !reader.isWhiteSpace()) { System. out .printf(&quot;%s - %s%n&quot;, element,    reader.getText()); } reader.next(); } reader.close()
Parsing Documents with the StAX Parser Live Demo
Creating Documents with the StAX Parser – Example String fileName = &quot;Customers.xml&quot;; FileWriter fileWriter = new FileWriter(fileName);  XMLOutputFactory factory = XMLOutputFactory. newInstance (); XMLStreamWriter writer = factory.createXMLStreamWriter(fileWriter); writer.writeStartDocument(); writer.writeStartElement(&quot;Customers&quot;); writer.writeStartElement(&quot;Customer&quot;); writer.writeStartElement(&quot;Name&quot;); writer.writeCharacters(&quot;ABC Pizza&quot;); writer.writeEndElement(); writer.writeStartElement(&quot;Address&quot;); writer.writeCharacters(&quot;1 Main Street&quot;); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.flush();
Parsing Documents with the StAX Parser Live Demo
Using XPath in Java Searching nodes in XML documents
Parsing XML Documents with XPath ,[object Object],[object Object],[object Object],[object Object],XPathFactory xpfactory = XPathFactory.newInstance();  XPath  x path = xpfactory.newXPath(); String result =  x path.evaluate(expression, doc)
Sample XML Document ,[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]
Parsing with XPath – Example ,[object Object],[object Object],String result =   xpath.evaluate(&quot;/items/item[2]/price&quot;, doc) NodeList nodes = (NodeList) xpath.evaluate( &quot;/items/item[@type='beer']/price&quot;, doc, XPathConstants.NODESET); for (int i=0; i<beerPriceNodes.getLength(); i++) { Node priceNode = nodes.item(i); System.out.println(node.getTextContent()); }
Using XPath Live Demo
Modifying XML with DOM and XPath Live Demo
XSL Transformations in JAXP javax.xml.transform.Transformer
XSLT API
Transforming with XSLT in Java with JAXP ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Transforming with XSLT in Java with JAXP (2) ,[object Object],[object Object],[object Object],TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer xslTransformer = tFactory.newTransformer( new StreamSource(&quot;style sheet .xsl&quot;)); xslTransformer.transform( new StreamSource(&quot;in put .xml&quot;), new Stream Result (&quot;out put .xml&quot;));
Transforming with XSL – Example <?xml version=&quot;1.0&quot;?> <library name=&quot;.NET Developer's Library&quot;> <book> <title>Programming Microsoft .NET</title> <author>Jeff Prosise</author> <isbn>0-7356-1376-1</isbn> </book> <book> <title>Microsoft .NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1-930110-19-7</isbn> </book> </library> library.xml
Transforming with XSL – Example (2) <?xml version=&quot;1.0&quot; encoding=&quot;windows-1251&quot;?> <xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;> <xsl:output method=&quot;xml&quot; encoding=&quot;utf-8&quot; indent=&quot;yes&quot; omit-xml-declaration=&quot;yes&quot;/> <xsl:template match=&quot;/&quot;> <html> <head> <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset= utf-8 &quot; /> </head> <body> <h1>Моята библиотека</h1> <table bgcolor=&quot;#E0E0E0&quot; cellspacing=&quot;1&quot;> (example continues) library-xml2html.xsl
Transforming with XSL – Example (3) <tr bgcolor=&quot;#EEEEEE&quot;> <td><b>Заглавие</b></td> <td><b>Автор</b></td> </tr> <xsl:for-each select=&quot;/library/book&quot;> <tr bgcolor=&quot;white&quot;> <td><xsl:value-of select=&quot;title&quot;/></td> <td><xsl:value-of select=&quot;author&quot;/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> library-xml2html.xsl
Transforming with XSL – Example (4) public class XSLTransformDemo { public static void main(String[] args)  throws TransformerException { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer xslTransformer = tFactory.newTransformer( new StreamSource(&quot;library-xml2html.xsl&quot;)); xslTransformer.transform( new StreamSource(&quot; library .xml&quot;), new StreamResult(&quot; library . ht ml&quot;)); } } XSLTransformDemo.java
Transforming with XSL – Example (5) <html> <head> <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot;/> </head> <body> <h1>Моята библиотека</h1> <table bgcolor=&quot;#E0E0E0&quot; cellspacing=&quot;1&quot;> <tr bgcolor=&quot;#EEEEEE&quot;> <td><b>Заглавие</b></td> <td><b>Автор</b></td> </tr> (example continues) Result : library.html
Transforming with XSL – Example (6) <tr bgcolor=&quot;white&quot;> <td>Programming Microsoft .NET</td> <td>Jeff Prosise</td> </tr> <tr bgcolor=&quot;white&quot;> <td>Microsoft .NET for Programmers</td> <td>Fergal Grimes</td> </tr> </table> </body> </html> Result : library.html
XSL Transformations Live Demo
Exercises ,[object Object],[object Object],[object Object]
Exercises (2) ,[object Object],[object Object],[object Object]
Exercises (3) ,[object Object],[object Object],[object Object],[object Object]
Exercises (4) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exercises (5) ,[object Object]

Mais conteúdo relacionado

Mais procurados (20)

PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
6. Utilización del modelo de objetos del documento (DOM)
6. Utilización del modelo de objetos del documento (DOM)6. Utilización del modelo de objetos del documento (DOM)
6. Utilización del modelo de objetos del documento (DOM)
 
Javascript
JavascriptJavascript
Javascript
 
Class Intro / HTML Basics
Class Intro / HTML BasicsClass Intro / HTML Basics
Class Intro / HTML Basics
 
Javascript
JavascriptJavascript
Javascript
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
Xml dtd
Xml dtdXml dtd
Xml dtd
 
Xml query language and navigation
Xml query language and navigationXml query language and navigation
Xml query language and navigation
 
XML
XMLXML
XML
 
Dom JavaScript
Dom JavaScriptDom JavaScript
Dom JavaScript
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
 
Querying XML: XPath and XQuery
Querying XML: XPath and XQueryQuerying XML: XPath and XQuery
Querying XML: XPath and XQuery
 
Oracle Application Express
Oracle Application ExpressOracle Application Express
Oracle Application Express
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
HTML5: features with examples
HTML5: features with examplesHTML5: features with examples
HTML5: features with examples
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 

Destaque (13)

WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
 
Formatting content in_word_(part_2)
Formatting content in_word_(part_2)Formatting content in_word_(part_2)
Formatting content in_word_(part_2)
 
Formatting content in_word_2010
Formatting content in_word_2010Formatting content in_word_2010
Formatting content in_word_2010
 
Views in word_2010
Views in word_2010Views in word_2010
Views in word_2010
 
Chapter.03
Chapter.03Chapter.03
Chapter.03
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
CSS
CSSCSS
CSS
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
 
Rich faces
Rich facesRich faces
Rich faces
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
 

Semelhante a Processing XML with Java

Semelhante a Processing XML with Java (20)

Sax Dom Tutorial
Sax Dom TutorialSax Dom Tutorial
Sax Dom Tutorial
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
 
test
testtest
test
 
6 311 W
6 311 W6 311 W
6 311 W
 
6 311 W
6 311 W6 311 W
6 311 W
 
5 xml parsing
5   xml parsing5   xml parsing
5 xml parsing
 
Web Services Part 1
Web Services Part 1Web Services Part 1
Web Services Part 1
 
Inroduction to XSLT with PHP4
Inroduction to XSLT with PHP4Inroduction to XSLT with PHP4
Inroduction to XSLT with PHP4
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-public
 
XML Transformations With PHP
XML Transformations With PHPXML Transformations With PHP
XML Transformations With PHP
 
Xml Java
Xml JavaXml Java
Xml Java
 
Xml Overview
Xml OverviewXml Overview
Xml Overview
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Xml
XmlXml
Xml
 
HTML5
HTML5HTML5
HTML5
 
[DSBW Spring 2010] Unit 10: XML and Web And beyond
[DSBW Spring 2010] Unit 10: XML and Web And beyond[DSBW Spring 2010] Unit 10: XML and Web And beyond
[DSBW Spring 2010] Unit 10: XML and Web And beyond
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
AD215 - Practical Magic with DXL
AD215 - Practical Magic with DXLAD215 - Practical Magic with DXL
AD215 - Practical Magic with DXL
 
XPath - XML Path Language
XPath - XML Path LanguageXPath - XML Path Language
XPath - XML Path Language
 

Mais de BG Java EE Course (20)

Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
JSTL
JSTLJSTL
JSTL
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
 
Strings v.1.1
Strings v.1.1Strings v.1.1
Strings v.1.1
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Algorithms with-java-1.0
Algorithms with-java-1.0Algorithms with-java-1.0
Algorithms with-java-1.0
 
Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 

Último

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 

Último (20)

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 

Processing XML with Java

  • 1. Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers www.devbg.org
  • 2.
  • 4.
  • 5.
  • 6.
  • 7.
  • 10.
  • 11.
  • 12.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25. Using the DOM Parser
  • 26. 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: <?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>
  • 27.
  • 29. Using DOM import javax.xml.parsers.*; import org.w3c.dom.*; // G et a DocumentBuilder object DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } // I nvoke 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:
  • 30.
  • 31. 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 ... e.g. DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE, COMMENT_NODE, etc.
  • 32. More Document Accessors 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 ...
  • 33.
  • 34. Reading and Parsing XML Documents with the DOM Parser Live Demo
  • 35.
  • 36. 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 ...
  • 37. Building Documents with the DOM Parser Live Demo
  • 38. Using The StAX Parser
  • 39.
  • 40. Parsing Documents with the StAX Parser – Example FileReader fileReader = new FileReader(&quot;Student.xml&quot;); XMLInputFactory factory = XMLInputFactory. newInstance (); XMLStreamReader reader = factory.createXMLStreamReader(fileReader); String element = &quot;&quot;; while (reader.hasNext()) { if (reader.isStartElement()) { element = reader.getLocalName(); } else if (reader.isCharacters() && !reader.isWhiteSpace()) { System. out .printf(&quot;%s - %s%n&quot;, element, reader.getText()); } reader.next(); } reader.close()
  • 41. Parsing Documents with the StAX Parser Live Demo
  • 42. Creating Documents with the StAX Parser – Example String fileName = &quot;Customers.xml&quot;; FileWriter fileWriter = new FileWriter(fileName); XMLOutputFactory factory = XMLOutputFactory. newInstance (); XMLStreamWriter writer = factory.createXMLStreamWriter(fileWriter); writer.writeStartDocument(); writer.writeStartElement(&quot;Customers&quot;); writer.writeStartElement(&quot;Customer&quot;); writer.writeStartElement(&quot;Name&quot;); writer.writeCharacters(&quot;ABC Pizza&quot;); writer.writeEndElement(); writer.writeStartElement(&quot;Address&quot;); writer.writeCharacters(&quot;1 Main Street&quot;); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.flush();
  • 43. Parsing Documents with the StAX Parser Live Demo
  • 44. Using XPath in Java Searching nodes in XML documents
  • 45.
  • 46.
  • 47.
  • 49. Modifying XML with DOM and XPath Live Demo
  • 50. XSL Transformations in JAXP javax.xml.transform.Transformer
  • 52.
  • 53.
  • 54. Transforming with XSL – Example <?xml version=&quot;1.0&quot;?> <library name=&quot;.NET Developer's Library&quot;> <book> <title>Programming Microsoft .NET</title> <author>Jeff Prosise</author> <isbn>0-7356-1376-1</isbn> </book> <book> <title>Microsoft .NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1-930110-19-7</isbn> </book> </library> library.xml
  • 55. Transforming with XSL – Example (2) <?xml version=&quot;1.0&quot; encoding=&quot;windows-1251&quot;?> <xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;> <xsl:output method=&quot;xml&quot; encoding=&quot;utf-8&quot; indent=&quot;yes&quot; omit-xml-declaration=&quot;yes&quot;/> <xsl:template match=&quot;/&quot;> <html> <head> <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset= utf-8 &quot; /> </head> <body> <h1>Моята библиотека</h1> <table bgcolor=&quot;#E0E0E0&quot; cellspacing=&quot;1&quot;> (example continues) library-xml2html.xsl
  • 56. Transforming with XSL – Example (3) <tr bgcolor=&quot;#EEEEEE&quot;> <td><b>Заглавие</b></td> <td><b>Автор</b></td> </tr> <xsl:for-each select=&quot;/library/book&quot;> <tr bgcolor=&quot;white&quot;> <td><xsl:value-of select=&quot;title&quot;/></td> <td><xsl:value-of select=&quot;author&quot;/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> library-xml2html.xsl
  • 57. Transforming with XSL – Example (4) public class XSLTransformDemo { public static void main(String[] args) throws TransformerException { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer xslTransformer = tFactory.newTransformer( new StreamSource(&quot;library-xml2html.xsl&quot;)); xslTransformer.transform( new StreamSource(&quot; library .xml&quot;), new StreamResult(&quot; library . ht ml&quot;)); } } XSLTransformDemo.java
  • 58. Transforming with XSL – Example (5) <html> <head> <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot;/> </head> <body> <h1>Моята библиотека</h1> <table bgcolor=&quot;#E0E0E0&quot; cellspacing=&quot;1&quot;> <tr bgcolor=&quot;#EEEEEE&quot;> <td><b>Заглавие</b></td> <td><b>Автор</b></td> </tr> (example continues) Result : library.html
  • 59. Transforming with XSL – Example (6) <tr bgcolor=&quot;white&quot;> <td>Programming Microsoft .NET</td> <td>Jeff Prosise</td> </tr> <tr bgcolor=&quot;white&quot;> <td>Microsoft .NET for Programmers</td> <td>Fergal Grimes</td> </tr> </table> </body> </html> Result : library.html
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.

Notas do Editor

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  2. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  5. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  6. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  7. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  8. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  9. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  10. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  11. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  12. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  13. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  14. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  15. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  16. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  17. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  18. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  19. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  20. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  21. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  22. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  23. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  24. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  25. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  26. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  27. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  28. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  29. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  30. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  31. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ## Any changes made since the last commit will be ignored – usually rollback is used in combination with Java’s exception handling ability to recover from unpredictable errors.
  32. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  33. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  34. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  35. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  36. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  37. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  38. (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##