0% found this document useful (0 votes)
29 views26 pages

WT Unit - 2

Uploaded by

roshanbi1231
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views26 pages

WT Unit - 2

Uploaded by

roshanbi1231
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT -2

XML
INTRODUCTION TO XML

what is XML :

*XML stands for Extensible Markup Language.

* XML is a markup language much like HTML.

* XML was designed to carry data, not to display data.

* XML tags are not pre defined. You must define your own tags.

* XML is designed to be self-descriptive.

* XML is W3C Recommendation

* XML is platform independent and language independent.

Representing Web Data: XML

XML stands for exentensible Markup Language, developed by W3c in 1996. XML 1.0
was officially adopted as a W3C recommendation in 1998.

XML was designed to carry data not to display data . XML is designed to self-
descriptive. XML is a subset of SGML that can be defined in your own tags. A meta
language and tags describe the content ,XML supports CSS,XSL,AND DOM

Html xml
HTML stands for hypertext Xml stands for extensible markup language
markup language

H T M L is a markup Xml provides a framework to define markup


language languages

H T M L is not case XML is a case sensitive


sensitive

Html tags are predefined XML tag are user defined tag
tag

It has an extension of . It has an extension of . X M L


html or .htm

There are limited number XML tags are extensible


of tracks in H T M L

In HTML, closing tax or In XML, closing tax are necessary


not necessary

It is used to display the It is used to store data


data
It does not carry data it It carries the data to and from database
just display it.

Some of the tools used for Some of the tools are used for xml are
html are oxygen xml
Visual Studio Code Xml notepad
Notepad ++ Liquid
studio and many Liquid studio and many more
more
Notepad And many
more
HTML:EXAMPLE XML:EXAMPLE
<html> <college>
<body> <class1>
<p>student1</p> <student>sukanya</student>
</body> </class1>
</html> </college>

Advantages of xml:-

It acts as a mini database

X M L is used to create new markup languages

Using XML, you can create your own text

XML is used to create structured data

XML is used to transfer data across applications on web

XML is language independent and platform independent

Features and Advantages

1. Platform independence: XML can be used on any platform, operating system, or


device.

2. Language independence: XML is not specific to any programming language.

3. Self-descriptive: XML documents contain information about their own structure


and content.

4. Easy to read and write: XML documents are human-readable and can be easily
written and edited.

5. Extensible: XML allows you to define your own tags and attributes, making it
highly extensible.

6. Open standard: XML is an open standard, maintained by the World Wide Web
Consortium (W3C).
7. Wide adoption: XML is widely adopted and supported by most programming
languages, tools, and technologies.

8. Data exchange: XML is ideal for exchanging data between different systems,
applications, and organizations.

9. Searching and querying: XML documents can be easily searched and queried
using technologies like XPath and XQuery.

10. Transformability: XML documents can be transformed into other formats, such
as HTML, CSV, or JSON, using XSLT.

 XML is a simple scripting language where as humans can easily read.


 XML document Is language natural that means one language programming
code can generate an XML document and these Documents can be passed by
other languages

Goals of XML:-

 The user must be able to define and use his own tags .
 Allows the user to build his own tag library, based on his web requirement.
 Allows user to define the formatting rules for the user defined tags.
 xml must support storage or transport of data
 XML should be easier to write programs

Define XML tax their attributes and values:-

Tags any elements:-

An xml file is structured by the several xml elements, also called the xml nodes or
xml tags. XML elements names an enclosed by the triangular brackets <> also
known below

<element/>

Syntax Rules for Tags and Elements

Element Syntax: Each XML-element needs to be closed either with start or with end
elements as shown below:

<element>....</element>

or in simple-cases, just this way: <element/>

Nesting of elements:

An XML-element can contain multiple XML-elements as its children, but


thechildren elements must not overlap. i.e., an end tag of an element must have the
same name as that of the most recent unmatched start tag.

Following example shows incorrect nested tags:


<?xml version="1.0"?>
<contact_info>
<company>TCS
</contact_info>
</company>

Following example shows correct nested tags:

<?xml version="1.0"?>
<contact_info>
<company>TCS</company>
<contact_info>

Let us learn about one of the most important part of XML, The XML tax form the foundation of
XML. They define the scope of an element in the xml they can also be used to insert comments
declare setting required for piercing the environment and the insert special instructions

We can broadly categorise X M L tags

Start tag:

The beginning of every non empty xml element is marked by a start tag. An example for the
start tag is

<address>

End tag:

Every element that has a start tag should end with an end-tag . An example for the end tag

is

</address>

* Note that the end tag includes a soliders (“/”) before the name of an element

Empty tag:

The text that appears between start tag and end-tag is called content. An element which is
no content is termed as empty An empty element can be represented in two ways as below:

(1) A start tag immediately follows by an end tag is also shown below:
<hr> </hr>
(2) A complete empty element tag is shown as below:
<hr/>

Empty element tag may be used for any element which has no content

Xml tags rules:

Following are the rules that need to be followed to use xml tags:

Rule 1:

XML tags are case-sensitive, following line of the code is an example for wrong syntax

</Address>

because of the case difference in two tags, which is created as erroneous syntax in XML

<address> this is wrong syntax</Address>

following code shows a correct way ,where we use the same case to name the start and the
end tag .

<address> this is correct syntax </address>

Rule 2:

XML tax must be closed in an appropriate order i.e., an XML tag opened inside another
element must be closed before the outer element is closed.

<outer_element>

<internal_element>
This tag is closer before the outer element
</internal_element>

</outer_element >

Xml elements:

Xml elements can be defined as a building blocks of an xml. Elements can behave as
containers to hold text, elements ,attributes, media objects or all of these.

* each Xml documents contains one or more elements, the scope of which are either
eliminated by start and end tags or for empty elements by an empty element tag

Syntax:

Following is the syntax to write an xml element

<element-name attribute1 attribute2>


.......content
</ element-name>

Where,
Element-name is the name of the element the name its case in the start and element tag must
match

Attribute1 ,attribute2 are attributes of the element separated by white space An attribute
defines a property of the element. It associate a name which with a value which is a string of
characters An attributes is written as:

name=”value”
The name is followed by an = sign and a string value inside double (“ “)or single (‘ ‘) quotes

Empty element:-
An empty element (element with no content) as following syntax:

< name attribute1 attribute2...../>

Example of an XML document using various xml elements:

<?xml version=”1.0”?>
<contact-info>
<address category=”residence”>
<name>xyz </name>
<company> tutorial point</company>
<phone>123456789</phone>
</address>
</contact-info>

Xml element rules:

Following rules are required to be following for the XML element:

An element name can contain any alphanumeric character. The only punctuation
mark allowed in names are the hyphen ( - ),underscore ( _ ) and period ( . )

Names are case sensitive for example Address,addressand address are different
names

start and end tags of an elements must be identical .

An element which is a container, can contain text or elements as seen in the above
example.
Root element:
An XML document can have only one root element. For example, following is not a correct
XML document, because both the x and y elements occur at the top level without a root
element:

<x>...</x>
<y>...</y>

The following example shows a correctly formed XML document:

<root>
<x>...</x>
<y>...</y>
</root>

Document type definition (DTD):


DTD is an xml technique used to define the structure of a xml document. Dtd is a text
based document with the extension of dot dtd defines the structure and the legal
elements or and attributes attributes of an xml document

DTD XML building blocks:


The main building block of the both xml and Html documents

 Seen from ADTD point of view at all. XML documents were made by the
following building blocks.
a) Elements
b) Attributes
c) Entities
d) PCDATA
e) C DATA
A) Elements

Declaring elements
In dtd xml elements are declared with the following syntax.

<!ELEMENT ELEMENT-NAME CATEGORY>

OR

<!ELEMENT ELEMENT-NAME(ELEMENT-CONTENT)>

Element with parsed character data


Elements with only parsed character data or declared with # PCDATA inside
Parathasis.

<!ELEMENT element-name(child)>

Or

<!ELEMENT element-name(child1,child2)>

Example:-

<!ELEMENT student (branch,rno,name,marks)>

<!ELEMENT student (branch,rno,name,marks)>

<!ELEMENT branch (#PCDATA)>

<!ELEMENT rno (#PCDATA)>

<!ELEMENT name(#PCDATA)>

<!ELEMENT marks (#PCDATA)>

Attributes:-

Declaring attributes <!ATTLIST element-name attribute-name attribute-type


attribute-value>

DTD EXAMPLE:- <!ATTLIST payment type CDATA “check”>

XML EXAMPLE:- <payment type=”check”/>

A default attribute value:-

DTD: <!ELEMENT square EMPTY>

<!ATTLIST square width CDATA “0”>

VALID XML:- <SQUARE WIDTH=”100”/>


#REQUIRED:-

DTD:- <!ATTLIST person number CDATA #REQUIRED>

Valid XML: <person number = "5677" />

Invalid XML: <person/>

#IMPLIED:-

DTD: <!ATTLIST contact fax CDATA #IMPLIED>

Valid XML: <contact fax="555-667788"/>

Valid XML: <contact />

#FIXED:

DTD: <!ATTLIST college name CDATA #FIXED "NNRG">

་Valid XML : <college name= "NNRG"/>

Invalid XML: <college name = “JNTUK”/>

Enumerated Attribute Values

DTD: <!ATTLIST payment type (check|cash) "cash">

XML example: <payment type="check" />

or

<payment type="cash" />

Example
//abc.dtd

<!ELEMENT student (branch,rno,name,marks)>

<!ELEMENT student (branch,rno,name,marks)>

<!ELEMENT branch (#PCDATA)>

<!ELEMENT rno (#PCDATA)>

<!ELEMENT name(#PCDATA)>

<!ELEMENT marks (#PCDATA)>


<ATTLIST branch dept CDATA #REQUIRED>

//abc.xml

<?xml version =”1.0”?>

<!DOCTYPE student system “abc.dtd”>

<student>

<branch dept=”mca”>

<rno>101</rno>

<name> pooja </name>

<marks > 65 </marks>

</branch>

</student>

Linking DTD to xml:-


DTD declaration, either internal xml document or make external dtd file after

linking to a xml document.

 Internal DTD you can write rules inside xml document using <!DOCTYPE..>
declaration. scope of this DTD within this document. Advantages is document
validated by itself, without external reference
 External DTD you can write rules in a separate file (with . dtd extension) later
this file linked to a xml document. This way you can linked several xml
documents refer same DTD rules

Internal DTD:-

Internal DTD. You can declare inside your xml file in xml file top <!DOCTYPE...>
declaration to declare the DTD

<?xml version =”1.0” standalone=”yes”?>

<!DOCTYPE root_element [

.........................

.......

]
Following internal DTD. Example, define root element <student> and other elements,
or second level element, along with the discipline attitude.

 DTD rules must be placed specifies top of the xml element ( root element) in the
document.

<?xml version= ”1.0” ?>

<!DOCTYPE root_element [

<!ELEMENT student (branch,rno,name,marks)>

<!ELEMENT branch (#PCDATA)>

<!ELEMENT rno (#PCDATA)>

<!ELEMENT name(#PCDATA)>

<!ELEMENT marks (#PCDATA)>

<ATTLIST branch dept CDATA #REQUIRED> ]

<student>

<branch dept=”mca”>

<rno>101</rno>

<name> pooja </name>

<marks > 65 </marks>

</branch>

</student>

External DTD:-
External duty are shared between multiple xml documents, any changes or updates
in DTD Document effects or update come to all xml documents

 External DTD of two types


a) Private DTD
b) Public DTD

Private DTD:-

Private DTD identified by the SYSTEM keyboard access for single or group of users.
You can specify the rules in the external dtd file with .dtd extension later in xml file.
<!DOCTYPE...> declaration is present to link the DTD file

Syntax:

<!doctype root_element SYSTEM “dtd-file-location”>

Example:-

<!DOCTYPE root_element SYSTEM “abc.dtd”>

Public DTD:-

Public DTD identified by the PUBLIC keyword access any users and our xml editor
are known as known to DTD

 Some common D T D R Webdt Xhtml Mathml ETC

Syntax:-
<!DOCTYPE root_element PUBLIC ”dtd-name” “dtd-file-location”>

Example:-
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN ”
“http://www.w3.org/TR/chtml1/DTD/Xhtml-transitional.dtd”>

XML SCHEMA:-
XML SCHEMA is commonly known as XML schema definition(XSD) . It

is used to describe and validate the structure and the content of the xml data. Xml
schema defines the elements, attributes and data types schema element supports
namespaces. It is similar to database schema that describes the data in the
database.

Syntax:-
The following example show how to use scheme

<?xml version="1.0"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="contact">

<xs:complexType>

<xs:sequence>

<xs:element name="name" type="xs:string"/>


<xs:element name="company" type="xs:string"/>

<xs:element name="hphone" type="xs:string"/>

</xs:sequence>

</xs:complexType>

</xs:element>

</xs:schema>

The basic idea behind XML schemes is that they describe the legitimate format that an
xml document can take

Elements
As we saw in xml element chapter elements are the building blocks of the XML
document an element can be defined within a XSD as follows

<xs: element name=”x” type=”y”/>

Definition types
You can define XML schema elements in the following ways

 Simple type
 Complex type
 Global Type

Simple type:-
Simple type element is used only in the context of the text. Some of the pre defined
simple types are

xs:integer, xs:Boolean, xs:string, xs:date.

For example:-
<xs:element name=”phone_number” type=”xs:int”/>

Complex type:-
A complex type is a container for other element definitions. This allows you to specify
which child element can contain and to provide some structure within your xml
documents.

<xs:element name="Address">

<xs:complexType>

<xs:sequence>

<xs:element name="name" type="xs:string"/>


<xs:element name="company" type="xs:string"/>

<xs:element name="phone" type="xs:string"/>

</xs:sequence>

</xs:complexType>

</xs:element>

In the above example, address element consists of child element. This is the container
of the <xs: element> definitions that allows to build a simple hierarchy of elements in
the xml document.

Global type:-
With the global type, you can define a single type in your document, which can be
used by War references for example, suppose you want to journalise the person and
company for different addresses of the company. In such case, you can define a
general type as follows

<xs:element name="Address">

<xs:complexType>

<xs:sequence>

<xs:element name="name" type="xs:string"/>

<xs:element name="company" type="xs:string"/>

<xs:element name="phone" type="xs:string"/>

</xs:sequence>

</xs:complexType>

</xs:element>

Now let us use this type in our example as follows

<xs:element name="Address 1">

<xs:complexType>

<xs:sequence>

<xs:element name="address" type="addresstype"/>

<xs:element name="phone 1" type="xs:int"/>

</xs:sequence>
</xs:complexType>

</xs:element>

<xs:element name="Address 2">

<xs:complexType>

<xs:sequence>

<xs:element name="address" type="addresstype"/>

<xs:element name="phone 2" type="xs:int"/>

</xs:sequence>

</xs:complexType>

</xs:element>

Instead of having to define the name and the company twice, (once for address one
and once for the address ), we now have a single definition This makes maintenance
simpler i.e., if you decide to add “postcode” element to the address you need to add
them at just one place.

Attributes:-

Attributes is XSD provides extra information within an element. Attributes have name
and type property as follows, as shown below

<xs: attributes name =”x” type=”y”/>

Document object model:


“The W3c (DOM) document object model is a platform and language netural interface
that allows programs and scripts to dynamically access and update the content
structure and style of a document”

The html DOM defines a standard way for accessing and manipulating html
documents. It presents the html documents as a tree structure.

In XML DOM is a standard for how to get ,change,Add or delete xml elements

In XML DOM we use few properties and methods.

XML PROPERTIES:

1) nodeName
2) node value
3) Parent Node
4) childNode
5) attributes

methods:-

1) getElmentByTagName(“ “)
2) appendChild(node);
3) removeChild(node);

Get the value of an xml element


Txt=xmlDoc.getElementByTagName(“title”)[0].childNodes[0].nodeValue;

Example:- xml program

<student>

<branch Br=”CSE”>

<rno> 101 <rno>

<title> xyz</title>

</branch>

<branch Br=”ECE”>

<rno> 102 <rno>

<title> abc </title>

</branch>

</student>

XML DOM nodes:-


According to the xml DOM everything is an xml document is a node.

The entire document is a document node


Every X M L element is an element node
The text in the xml element or text nodes
Every attribute is an attribute node
Comments or comment Nodes

Insert a new node in XML:

For inserting a new element, we can use append child, which insert a child node to a
specified tag

X= document.appendChild(“marks”)

Example:-
getElementByTagName(‘dept’)[1].childNode[0].nodeValue=240;

program:-

<college>

<dept Branch=’CSE’>

<student> 120 </student>

<faculty> 30 </faculty>

</dept>

<dept Branch=’ECE’>

<student> 115 </student>

<faculty> 30 </faculty>

</dept>

</college>

In the above example, instead of 120 we get 240

Create a new element:-

newElement=xmlDoc.CreateElement(“lab”);

xmlDoc.getElementByTagName (“dept”) [0]. appendChild(newElement);

In javascript we write document

In XML, we write Doc

To insert value into that:-


xmlDoc.getElementByTagName (“dept”) [0] . childNode[2]. nodeValue=5;

Create an attribute:-
xmlDoc.getElementByTagName (“dept”) [2] . setAttribute(‘ branch’ , ’ mech ’ );

For deleting or removing:-


xmlDoc.getElementByTagName (“dept”) [0] . childNode[1]. nodeValue=” “;

To remove child:-
xmlDoc.getElementByTagName (“dept”) [0] . childNode[2]. Removechild ( );
XHTML
XHTML is html written as xml

What is xhtml?
 xhtml stands for Extensible Hypertext Markup language
 X H T M L is almost identical to H T M L
 XHTML is supported by all major browsers

xhtml elements:-
xhtml elements must be properly nested

xhtml elements must always be closed

xhtml elements must be in lower case

XHTML documents must have one root

XHTML attributes:-
Attributes name must be in lower case

Attribute to values must be quoted

Attribute minimization is forbidden

<!DOCTYPE....> is mandatory:-
 An xhtml document must have a xhtml doctype declaration.
 A complete list of all the exhtml doc types is found in our html tax reference
 The <html> <head> <title> and <body> Elements must also be present and the
xml ns attribute in html must specify the hml namespace for the document
 Xhtml elements must always be closed
 Empty elements must always be closed
 XHTML elements must be in lower case.
 Xhtml attributes name must be in the lower case
 Attribute values must be quoted
XML namespace:-
 XML namespace provides a method to avoid element named conflicts
 To avoid such type of conflicts We use a name prefix

Example:-
Instead of <table>, we write <f :table> for all children of table. It should be started
/ended with the same prefix ‘ f ’

<f:table>
<f:tr>

<f:td> </f:td>

<f:td> </f:td>

</f:tr>

</f:table>

Note:-

XMLNS attribute in Html Specifies the xml namespace for a document. This attribute
will be added to first element of your xml

Example:- <Table xmlns : “filename”>

Structure of xhtml:-

1. Doctype
2. Header .
3. Body

//Create a student table, which has two columns, row number and name with three
rows.

Student .xhtml
<!doctype html public “_//w3c//DTD xhtml

1.0 transitional //EN “ “http: // www . w3.org / TR/ xhtml / DTD xhtml . dtd ‘ >

<.html xmlns =” http://www.w3.org/1999/xhtml”>

<head> </head>

<body>

<table>

<tr>

<th> Rno </th>

<th> name </th>

</tr >

<tr>

<td> 501 </td>

<td> harika </td>

</tr>

<tr>
<td> 502 </td>

<td> pooja </td>

</tr>

<tr>

<td> 503 </td>

<td> bujji </td>

</tr>

</table>

</body>

</html>

Parsing XML DATA:-

We can access and parse the external document in Two ways.

 Parsing using DOM ( tree based)


 Parsing using SAX (event based)

*parsing the Xml Doc using Dom methods and properties are called a tree based
approach. Whereas use SAX (simple api for XML) methods and properties are
called as event based approach

Xml
parsing

Object
based(eg:
EVENT
DOM)
based

Push Pull
parsing(eg:SAX) parsing(eg:-
stAX

DOM AND SAX parsers:-

DOM SAX
1) Tree data structure 1) Event based model.
2) Random access 2) serial access.
3) high memory usage 3) low memory usage.
4) used to process multiple lines( 4) used to process the document only
document is loaded in memory) once.
5) used to edit the document 5) used to process parts of the
document
6) Stores the entire external 6) parses node by node
document into memory before
Processing
7) Occupies more memory 7) Doesnt store the xml in memory
8) We can insert or delete nodes 8) We can’t insert an or delete nodes
9) Traverse in any direction 9) Top to bottom of traversing
10) Document object model (DOM) 10) SAX is a central API for XML
11) Import javax.xml.parsers.x; 11) Packages required to import
Import javax.xml.parsers.*;
Import Import org .xml.sax.*;
javax.xml.parsers.documentBuilder;

Importjavax.xml.parsers.
documentBuilder
Factory;
12)DOM is slow rather than SAX. 12) SAX Generally Run a little faster
than DOM.

Document object model is far defining the standard for accessing and
manipulating xml documents Xml DOM is used for
loading the xml document
accessing the xml document,
deleting the element of xml document
changing the xml elements of xml document,
according to the dom everything is an Xml document is a node it considers
the entire document is a document node.
Every xml element is an element node.
The text in the xml element is a text nodes.
Every attribute is an attribute node.
comments or comment nodes

Dom based XML parsing:-

Dom Parser, parses the entire XML documents and loads it into memory. Then models it in a
“tree” structure for easy traversal or manipulation.

In short, it turns a xml file into DOM or tree structure. And you have to traverse a
node by node to get what you want.

Document builder
factory

Document (DOM)
Object

object object

Document
XML Data object object
In this approach to access xml document object model implementation is defined in the
following packages.

 Java X.xml parsers


 org.w3C.dom
The following Dom Java classes are necessary to process the XML document
Document builder factory class creates the instance of document builder
Document builder produces a document, (a Dom) that conforms to DOM specification

The following methods and properties are necessary to process the xml document

property meaning
Node name Finding the name of the node

Node value Obtaining value of the node

Parent node To get parent node

Child nodes Obtain child nodes

attributes For getting the attribute values

Method meaning
Getelementbytagname(name) To access the element by specifying its name

Append child (node) To insert a child node

Remove child (node) To remove existing child node

Java programme to create xml file:-

import org.w3c. dom *;

import javax.xml. parsers.*;

import javax.xml. transform. *;

Import javax.xml transform. dom. *;

import java.util. Scanner;


import javax.xml. transform. stream.*;

import java.io.*;

public class Create XML

public static void main(String[] args) throws Exception

DocumentBuilderFactory factory = Document BuilderFactory new Instance();

DocumentBuilder builder = factory. new Doument Builder();

Document doc = builder new Document ();

Element rootele = doc. create Element ( student-details");

Element studentele = doc. create Element ("student");

Element idele = doc.createElement ("studentid");

Element nameele doc. Greate Element ("name");

Element markesele=doc GeateElement (“marks”);

Text t1 = doc. Greate Text Mode ("501');

Text t2 = doc create TextNode (naveen");

Text t3 = doc. cicate Text Node ("10");

idele appendChild (t1);

nameele appendChild (t2);

mark sele.appendChild (63);

studentele appendChild (idele);

studentele append Child (namele);

studentele appendChild (marks ele);

rootele.appendChild (studentele );

doc .append Child (rootele);

Transformer t = Transformer Factory.newInstance() new Transformer();

t. transform (new DOM Source (doc), new Stream Result (newFileOutputStream


("Student xml")));

Above code will generate an xml file with a name student.xml

Student xml:-
<?xml version="1.0" encoding ="UTF-8" standalone = "no" ?>

<student details>

<student>

<studentid > 501 </student id>

<name> naveen </name>

<marts > 90 < /marks>

</student>

</student-details>

Using sax Parser:-

SAX parser is different from the Dom Parser, where SAX Parser doesn’t load the complete xml
into the memory instead. It parses the xml line by line triggering different events as and when
it encounters different elements, like opening tag, closing tag character data and comments
and so on. This is the reason why SAX parser is called an event based parser

Along with the XML source file, we also register a handler which extends the default handler
class. The default handler class provides different call backs out of which we Would be
interested in

startElement( ):- Triggers this event when the start of the tag is encountered

endElement( ):- Triggers this event when the end of the tag is encountered

character( ):- Triggers this event when it encounters some text data

Startdocument( )

Startelement( )
XML
document Characters( )
SAX Content handler
parser endElements( )

Enddocument( )
Let's create a demo Program to read xml file with SAX parser to understand fully.

Student. xml

<?xml version = "l:0" encoding = "UTF- a" ?>

<student - details >

<student >

< student id> 501 </studentid>

< name > Ranu< /name >

<gender> Male < /gender>

</student >

<student>

<studentid > 502 < /studentid>

<name > Mahit < /name >

<address > BHEL </address >

<gender>Male < /gender>

< /student >

<(student -details>

Java program to read data from xml (student.xml) file

import java i0. * ;

import javax. Xml .parsers. SAx Parser ;

import javax .xml .parsers . SAX Parserfactory ;

import org .xml. Sax. Attributes ;

import org. Xml Sax. SAXExcepion ;

import org. Xml .Sax. helpers.DefautHandler ;

public class SAxParserDemo extends DefaultHandle


{

public void startDocunent( )

System .out .println (“begin parsing document );

public void startElement (String url,string local name,string qname,attributes att

System. Out. print ("<+qName + ">”);

public Void characters( char[] ch, int start, int length)

For(int i= start ; i< (start + length); i++)

System. out .print ( ch [i] );

public void endElement (Sring url, String localname, string qname )

System .out .print ("</'+ qName +">”);

Public void endDocument( )

System.out.println(“End parsing document”);

public static void main (String[ ] arg throws exception

SAX Parser P= SAXParserfactory. newInstance () .new SAXparser( ) ;

P .parse (new FileInput Stream (“student.xml”), new SAXParserDemo ( ) );

You might also like