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

Weitere ähnliche Inhalte

Was ist angesagt?

Images and Tables in HTML
Images and Tables in HTMLImages and Tables in HTML
Images and Tables in HTML
Aarti P
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Div tag presentation
Div tag presentationDiv tag presentation
Div tag presentation
alyssa_lum11
 

Was ist angesagt? (20)

JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Css Ppt
Css PptCss Ppt
Css Ppt
 
Learning HTML
Learning HTMLLearning HTML
Learning HTML
 
Images and Tables in HTML
Images and Tables in HTMLImages and Tables in HTML
Images and Tables in HTML
 
02 well formed and valid documents
02 well formed and valid documents02 well formed and valid documents
02 well formed and valid documents
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
Learning Html
Learning HtmlLearning Html
Learning Html
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
Xpath.ppt
Xpath.pptXpath.ppt
Xpath.ppt
 
Xml
XmlXml
Xml
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Html5 semantics
Html5 semanticsHtml5 semantics
Html5 semantics
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 
Css lecture notes
Css lecture notesCss lecture notes
Css lecture notes
 
Div tag presentation
Div tag presentationDiv tag presentation
Div tag presentation
 
Intro to JSON
Intro to JSONIntro to JSON
Intro to JSON
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Introduction to the DOM
Introduction to the DOMIntroduction to the DOM
Introduction to the DOM
 

Andere mochten auch (12)

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
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
 

Ähnlich wie Processing XML with Java

Web Services Part 1
Web Services Part 1Web Services Part 1
Web Services Part 1
patinijava
 
Xml Java
Xml JavaXml Java
Xml Java
cbee48
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
chomas kandar
 

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

Mehr von BG Java EE Course

JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 

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

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 

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.

Hinweis der Redaktion

  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.* ##