shanmugasundari.files.wordpress.com€¦  · web viewparsing xml – using dom, sax – xml...

19
UNIT II BUILDING XML- BASED APPLICATIONS Parsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING DOM Definition: DOM Need of DOM Disadvantages of DOM DOM levels DOM core DOM Traversal and Range Other DOM Implementation JAXB Definition: DOM DOM provides a way of representing an XML document in memory so that it can be manipulated by software Need of DOM To create and modify an XML document programmatically Considerable time taken to leverage existing parsers Disadvantages of DOM DOM can be memory intensive DOM is not practical for small devices such as PDAs and cellular phones DOM levels Level 1:Traversal of an XML document as well as manipulation of the content in that document Level2:Extends level 1 by adding additional features like namepace,events,ranges and so on Level3:Currently working draft DOM Traversal NodeIterator—Represents a sub tree of a liner list

Upload: others

Post on 26-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

UNIT II

BUILDING XML- BASED APPLICATIONS

Parsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML.

PARSING XML USING DOM

• Definition: DOM• Need of DOM• Disadvantages of DOM• DOM levels• DOM core• DOM Traversal and Range• Other DOM Implementation• JAXB

Definition: DOM• DOM provides a way of representing an XML document in memory so that it can be

manipulated by software Need of DOM• To create and modify an XML document programmatically• Considerable time taken to leverage existing parsers

Disadvantages of DOM• DOM can be memory intensive• DOM is not practical for small devices such as PDAs and cellular phones

DOM levels• Level 1:Traversal of an XML document as well as manipulation of the content in that

document• Level2:Extends level 1 by adding additional features like namepace,events,ranges and so

on• Level3:Currently working draft

DOM Traversal• NodeIterator—Represents a sub tree of a liner list• TreeWalker—Represents a subtree view• NodeFilter-Conjunct with above two ,to select specific nodes• DocumentTraversal-Method to create NodeIterator and TreeWalker

DOM Range• Range—Range which contains methods to define delete insert content• DocumentRange—Create a range

Other DOM Implementation• JDOM—API for XML accepted by Java Community

Page 2: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

• NanoXML-Smaller document (6KB to 33KB)• TinyXML—Reading document• kXML—J2ME

DOM Example:

package com.beingjavaguys.core;

import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class ReadXml { public static void main(String argv[]) { try {

File xmlFile = new File("C:/Users/sundari/Documents/XML/XMLDOM.xml"); DocumentBuilderFactory documentFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder documentBuilder = documentFactory .newDocumentBuilder(); Document doc = documentBuilder.parse(xmlFile);

doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("student");

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

for (int temp = 0; temp < nodeList.getLength(); temp++) { Node node = nodeList.item(temp);

System.out.println("\nElement type :" + node.getNodeName());

if (node.getNodeType() == Node.ELEMENT_NODE) {

Element student = (Element) node;

System.out.println("Student id : "

sundari, 02/01/17,
FileStreams
sundari, 02/01/17,
Array of list that can store the elements
sundari, 02/01/17,
Assessing the element name
sundari, 02/01/17,
Assessing the elements by its tag name
sundari, 02/01/17,
Assessing root element
sundari, 02/01/17,
Create the instances for classes
sundari, 02/01/17,
DOM Packages
sundari, 02/01/17,
Classes for DOM
Page 3: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

+ student.getAttribute("id")); System.out.println("First Name : " + student.getElementsByTagName("firstname").item(0) .getTextContent()); System.out.println("Last Name : " + student.getElementsByTagName("lastname").item(0) .getTextContent()); System.out.println("Email Id : " + student.getElementsByTagName("email").item(0) .getTextContent()); System.out.println("Phone No : " + student.getElementsByTagName("phone").item(0) .getTextContent());

} } } catch (Exception e) { e.printStackTrace(); } }}

XMLDOM.xml<?xml version="1.0"?><school> <student id="1"> <firstname>Maha</firstname> <lastname>rani</lastname> <email>[email protected]</email> <phone>7678767656</phone> </student> <student id="2"> <firstname>aarti</firstname> <lastname>shankar</lastname> <email>[email protected]</email> <phone>9876546545</phone> </student></school>

Output:

Page 4: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

JAXB:• JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert

Java object to / from XML file. – Marshalling – Convert a Java object into a XML file.– Unmarshalling – Convert XML content into a Java Object.

JAXB-Example

Customer-Class:

package com.java.core;

import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElementpublic class Customer { String name;

int age;int id;

public String getName() {return name;

}

@XmlElementpublic void setName(String name) {

this.name = name;}

public int getAge() {return age;

Page 5: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

}

@XmlElementpublic void setAge(int age) {

this.age = age;}

public int getId() {return id;

}

@XmlAttributepublic void setId(int id) {

this.id = id;}

}JAVAXB-Program:package com.java.core;

import java.io.File;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;

public class JAXBExample {public static void main(String[] args) {

Customer customer = new Customer(); customer.setId(100); customer.setName("mkyong"); customer.setAge(29);

try {

File file = new File("C:\\file.xml");JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printedjaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(customer, file);jaxbMarshaller.marshal(customer, System.out);

} catch (JAXBException e) {e.printStackTrace();

}

}}

Page 6: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

Output:

PARSING XML-SAX

• Definition: SAX • Need of SAX • Disadvantages of SAX • SAX vs DOM • SAX versions • SAX Basics• Example-SAX

Definition: SAX• SAX is an API that can be used to parse XML document.• It provides a framework for defining event listeners, or handlers. These handlers are

written by developers interested in parsing documents with a known structure Need of SAX:

SAX is a good way to write a tool or standalone program to process XML SAX parser can validate document against DTD SAX is completely free it can be easily embedded in a larger application without royalty

fees and copyright notices.SAX vs DOM

SAX is much simpler than DOM In SAX we no need to model every possible type of object that can be found in XML

document SAX is an event based API

Page 7: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

DOM parses XML in space where SAX parses XML in time.Disadvantages of SAX

SAX can be a bit harder to visualize compared to DOM because it is event driven model SAX is read only parser There is no formal specification for SAX Handling parent child relationship is complex

SAX Versions: SAX 1.0 SAX 2.0

 SAX callback methods : startDocument() and endDocument() – Method called at the start and end of an XML

document. startElement() and endElement() – Method called at the start and end of a document

element. characters() – Method called with the text contents in between the start and end tags of an

XML document element.

Example-SAX:

import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;

public class SAX { public static void main(String argv[]) { try {

SAXParserFactory factory = SAXParserFactory.newInstance();SAXParser saxParser = factory.newSAXParser();DefaultHandler handler = new DefaultHandler() {boolean bfname = false;boolean blname = false;boolean bnname = false;boolean bsalary = false;public void startElement(String uri, String localName,String qName,

Attributes attributes) throws SAXException {System.out.println("Start Element :" + qName);if (qName.equalsIgnoreCase("FIRSTNAME")) {

bfname = true;}if (qName.equalsIgnoreCase("LASTNAME")) {

blname = true;}

sundari, 02/01/17,
SAX Event
sundari, 02/01/17,
Create a class for SAX with event handler,Create a SAX parser
Page 8: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

if (qName.equalsIgnoreCase("NICKNAME")) {bnname = true;

}if (qName.equalsIgnoreCase("SALARY")) {

bsalary = true;}

}public void endElement(String uri, String localName,

String qName) throws SAXException {System.out.println("End Element :" + qName);}public void characters(char ch[], int start, int length) throws SAXException {

if (bfname) {System.out.println("First Name : " + new String(ch, start, length));bfname = false;

}if (blname) {

System.out.println("Last Name : " + new String(ch, start, length));blname = false;

}if (bnname) {

System.out.println("Nick Name : " + new String(ch, start, length));bnname = false;

}if (bsalary) {

System.out.println("Salary : " + new String(ch, start, length));bsalary = false;

}}

}; saxParser.parse("c:\\file1.xml", handler); } catch (Exception e) { e.printStackTrace(); } }}

XML file

file1.xml:

<?xml version="1.0"?><company>

<staff><firstname>yong</firstname><lastname>mook kim</lastname><nickname>mkyong</nickname>

sundari, 02/01/17,
Access the xl file to parse
sundari, 02/01/17,
SAX Event
Page 9: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

<salary>100000</salary></staff><staff>

<firstname>low</firstname><lastname>yin fong</lastname><nickname>fong fong</nickname><salary>200000</salary>

</staff></company>

Output:

Page 10: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

Transforming XML using XSLTDefinition:

XSL ( EXtensible Stylesheet Language) is a styling language for XML.  XSL describes how the XML elements should be displayed. XSLT stands for XSL Transformations. XSLT is used to transform XML documents into other formats (like transforming XML into HTML).

Syntax:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

XSLT Elements:

<xsl:template> Element

<xsl:template> element is used to build templates.The match attribute is used to associate a template with an XML element. The match attribute can also be used to define a template for the entire XML document. The value of the match attribute is an XPath expression (i.e. match="/" defines the whole document).

Syntax:

<xsl:template     match="/">…………..</xsl:template>

<xsl:value-of> Element

The <xsl:value-of> element can be used to extract the value of an XML element and add it to the output stream of the transformation

Syntax:

<xsl:value-of select="path" />

<xsl:for-each> Element

The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set:

Syntax:

<xsl:for-each select="catalog/cd">…………………… </xsl:for-each>

<xsl:sort>

To sort the output, simply add an <xsl:sort> element inside the <xsl:for-each> element in the XSL file

sundari, 02/02/17,
The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform>.
Page 11: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

Syntax:

<xsl:for-each select="path">      <xsl:sort select="path"/>……………./xsl:for-each>

<xsl:if> Element

To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL document.

Syntax:

<xsl:if test="expression">  ...some output if the expression is true...</xsl:if>

<xsl:choose>

<xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express multiple conditional tests.

Syntax:

<xsl:choose>  <xsl:when test="expression">    ... some output ...  </xsl:when>  <xsl:otherwise>    ... some output ....  </xsl:otherwise></xsl:choose>

<xsl:apply-templates>

<xsl:apply-templates> element applies a template to the current element or to the current element's child nodes. If we add a select attribute to the <xsl:apply-templates> element it will process only the child element that matches the value of the attribute. We can use the select attribute to specify the order in which the child nodes are processed.

Syntax:

<xsl:apply-templates  select="title"/>

Example:

Create an XSL Style Sheet: bookcatalog.xsl

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

Page 12: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

<html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each> </table> </body> </html></xsl:template>

</xsl:stylesheet>

Link the XSL Style Sheet to the XML Document - book.xml

<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?><catalog> <cd> <title>XML and Web service</title> <artist>RON</artist> <country>USA</country> <company>XMLNET</company> <price>600</price> <year>1985</year> </cd>..</catalog>

Sample Output:

Page 13: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

MODELING DATABASES in XML

The following seps to be followed to illustrate the connection of database with XML

1.Review the database schema2.Construct the desired XML document3.Define a schema for the XML document4.Create the JAXB binding schema5.Generate the JAXB classes based on the schema6.Develop a Data Access Object(DAO)7.Develop a servlet for HTTP access.1.Review the database schemaThe database should be created with field and its type of dataFor Example: Field Typename VARCHAR2Prop_num NUMBER

2.Construct the desired XML documentXML document should be prepared based on the data. The corresponding element tag should be mapped with the field in the databaseFor ExampleDatabase Field XML Element namename <prop_name>Prop_num <prop_num>

Page 14: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

3.Define a schema for the XML document

Based on the desired document format, we can create a schema definition. Most properly DTD schema format was chosen because JAXB supports only DTDsFor Example:

<!ELEMENT prop_name (#PCDATA)><!ELEMENT prop_num(#PCDATA)>

4.Create the JAXB binding schema JAXB binding schema is an XML document that contain instructions on how to bind a DTD to a Java Class.Using JAXB binding schema,we can define the names of the generated Java Classes, map element names to specific properties in the Java class,and provide the mapping rules for attributes.

Example

<element name=”rental_prop_list” type=”class” root=”true”/>

5.Generate the JAXB classes based on the schemaGenerate the Java source files based on our schemas.JAXB provides a schema compiler for generating the Java source files. The schema compiler takes as input the DTD and the JAXB binding Schema.

6.Develop a Data Access Object(DAO)A Data Access Object provides access to the backend database.The goal of the DAO design pattern is to provide a higher level of abstraction for database access.The DAO encapsulates the complex JDBC and SQL calls.The DAO provides access to backend database via public methods.The DAO converts a result set to a collection of objects.The object model the data stored in the database

Page 15: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

7.Develop a servlet for HTTP access.

The constructed DAO object is capable of retrieving information from a database and providing a collection of objects. By JAXB framework these objects can be marshaled into XML Servlet is needed to handle the requests to the DAO In the servlet we can call the appropriate method and return the result as an XML document.

Page 16: shanmugasundari.files.wordpress.com€¦  · Web viewParsing XML – using DOM, SAX – XML Transformation and XSL – XSL Formatting Modeling Databases in XML. PARSING XML USING

Testing the Application &JSP page

1.Open Microsoft command prompt window2.Move the source code directory3.Setup the classpath 4.Move to source code directory5.Compile the code6.Finally access the JSP page in web browser