Why Is XML So Important?
Why Is XML So Important?
Why Is XML So Important?
In XML opening and closing tags must therefore be written with the same case:
<message>This is correct</message
XML Elements Must be Properly Nested
Improper nesting of tags makes no sense to XML.
In HTML some elements can be improperly nested within each other like this:
<b><i>This text is bold and italic</b></i>
In XML all elements must be properly nested within each other like this:
<b><i>This text is bold and italic</i></b>
XML is a Complement to HTML
XML is not a replacement for HTML.
It is important to understand that XML is not a replacement for HTML. In Web development it
is most likely that XML will be used to describe the data, while HTML will be used to format
and display the same data.
The syntax rules for XML are very simple and strict. These are easy to learn and use.
Because of this, creating software that can read and manipulate XML is very easy. Xml enables
an user to create his own tags.
Note - XML documents use a self-describing and simple syntax
The XML declaration: Always the first line in the xml document:
The XML declaration should always be included. It defines the XML version and the character
encoding used in the document. In this case the document conforms to the 1.0 specification of
XML and uses the ISO-8859-1 (Latin-1/West European) character set.
<?xml version="1.0" encoding="ISO-8859-1"?>
Root Element: The next line defines the first element of the document . It is called as the root
element
<E-mail>
Child Elements: The next 4 lines describe the four child elements of the root (To, From, Subject
and Body).
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u
tonight</Body>
And finally the last line defines the end of the root element .
</E-mail>
you may feel from this example that the XML document contains a E-mail To Rohan From
Amit. Don't you agree that XML is quite self-descriptive?
Now let's discuss its syntax-rules which are very simple to learn.
All XML elements must have a closing tag
In XML all the elements must have a closing tag like this:
<To>Rohan</To>
<From>Amit</From>
<subchild>.....</subchild>
</child>
</root>
Comments in XML
The syntax for writing comments in XML is similar to that of HTML.
<!-- This is a comment -->
XML elements can have attributes in the start tag, just like HTML. Attributes are used to provide
additional information about elements. Attributes often provide information that is not a part
of the data. In the example below, the file type is irrelevant to the data, but important to the
software that wants to manipulate the element:
<file
type="gif">roseindia.gif</file>
Use the quote styles: "red" or 'red'
Attribute values must always be enclosed in quotes. Use either single or double quotes eg..
<color="red">
or like this:
<color='red'>
Note: If the attribute value itself contains double quotes it is necessary to use single quotes, like
in this example:
<name='Rose "India" Net'>
Note: If the attribute value itself contains single quotes it is necessary to use double quotes, like
in this example:
<name="Rose 'India' Net">
XML Validation
A "Valid" XML document is a "Well Formed" XML document, which also conforms to the
rules of a Document Type Definition (DTD) or a XML Schema .
The following xml document is validated against a DTD , notice the highlighted text.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE e-mail SYSTEM "InternalE-mail.dtd">
<E-mail>
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u tonight</Body>
</E-mail
XML DTD
A DTD defines the legal elements of an XML document. The purpose of a DTD is to define
the legal building blocks of an XML document. It defines the document structure with a list of
legal elements.
XML Schema
XML Schema is an XML based alternative to DTD .W3C supports an alternative to DTD
called XML Schema.
A Document Type Definition (DTD) defines the legal building blocks of an XML document. It
defines the document structure with a list of legal elements and attributes.
A DTD can be defined inside a XML document, or a external reference can be declared .
Internal DTD
If the DTD is defined inside the XML document, it should be wrapped in a DOCTYPE
definition with the following syntax:
<!DOCTYPE root-element [element-
declarations]>
Open the file E-mail.xml in a web-browser . you will see the following :
External DTD
If the DTD is defined in an external file, it should be wrapped in a DOCTYPE definition with
the following syntax:
<!DOCTYPE root-element SYSTEM
"filename">
This is the same XML document as above,(but with an external DTD ) : E-mail.xml
<?xml version="1.0"?>
<!DOCTYPE E-mail SYSTEM
"E-mail.dtd">
<E-mail>
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will
catch u tonight</Body>
</E-mail>
And this is the file "E-mail.dtd" which contains the following DTD:
<!ELEMENT E-mail (To,From,subject,Body)>
<!ELEMENT To (#PCDATA)>
<!ELEMENT From (#PCDATA)>
<!ELEMENT Subject (#PCDATA)>
<!ELEMENT Body (#PCDATA)>
Importance of a DTD?
• With a DTD, a XML file carries a description of its own format.
• With a DTD, independent groups of people can agree to use a standard DTD
for interchanging data.
• User application can use a standard DTD to verify that the data he receives
from the outside world is valid.
• User can also use a DTD to verify his own data.
Attributes
< <
> >
& &
" "
' '
PCDATA:
PCDATA means parsed character data. It can be thought as the character data ( text ) found
between the start tag and the end tag of a XML element.
PCDATA is a text to be parsed by a parser. The text is checked by the parser for entities
and markup.
Tags inside the text will be treated as markup and entities will be expanded. However, parsed
character data should not contain any &, <, or > characters. These should be represented by the
& , <, and > entities, respectively.
CDATA:
CDATA is character data that will NOT be parsed by a parser. Tags inside the text will
NOT be treated as markup and entities will not be expanded.
DTD-Elements
Empty Elements
Empty elements are declared with the keyword EMPTY inside the parentheses.
<!ELEMENT element-name
EMPTY>
DTD Example: <!ELEMENT br EMPTY>
In XML document:
<br />
When children are declared in a sequence separated by commas, the children must appear in the
same sequence in the document. In a full declaration, the children must also be declared.Children
can have children. The full declaration of the "E-mail" element is:
<!ELEMENT E-mail
(To,From,Subject,Body)>
<!ELEMENT To (#PCDATA)>
<!ELEMENT From (#PCDATA)>
<!ELEMENT Subject
(#PCDATA)>
<!ELEMENT Body (#PCDATA)>
The example above declares that the child element "Fill-Red" must occur once, and only once
inside the "color" element.
Declaring Minimum One Occurrence of an Element
<!ELEMENT element-name
(child-name+)>
DTD Example:
<!ELEMENT color (Fill-
Red+)>
The '+' sign in the example above declares that the child element "Fill-Red" must occur one or
more times inside the "color" element.
Declaring Zero or More Occurrences of an Element
<!ELEMENT element-name
(child-name*)>
DTD Example:
<!ELEMENT color (Fill-
Red*)>
The '*' sign in the example above declares that the child element "Fill-Red" can occur zero or
more times inside the "color" element.
Declaring Zero or One Occurrence of an Element
<!ELEMENT element-name
(child-name?)>
DTD Example:
<!ELEMENT color (Fill-Red?)>
The '?' sign in the example above declares that the child element "Fill-Red" can occur zero or
one time inside the "color" element.
Declaring either/or Content
DTD Example:
<!ELEMENT E-mail
(To,From,Subject,(Message|Body))>
The example above declares that the "E-mail" element must contain a "To" element, a "From"
element, a "Subject" element, and either a "Message" or a "Body" element.
Declaring Mixed Content
DTD Example:
<!ELEMENT E-mail(#PCDATA|To|
From|Subject|Body)*>
The example above declares that the "E-mail" element can contain zero or more occurrences of a
parsed character data, "To", "From", "Subject", or "Body" elements.
DTD-Attributes
Declaring Attributes
The ATTLIST declaration defines the element having a attribute with attribute name , attribute
type , and attribute default value. An attribute declaration has the following syntax:
Attribute-type
The attribute-type can be one of the following:
Type Description
Default-value
The default-value can be one of the following:
Value Explanation
REQUIRED
Syntax
<!ATTLIST element-name attribute_name
attribute-type #REQUIRED>
DTD Example
<!ATTLIST person number CDATA
#REQUIRED>
Valid XML:
<person id="5677"
/>
Invalid XML:
<person
/>
Use the #REQUIRED keyword if you don't have an option for a default value, but still want to
force the attribute to be present.
IMPLIED
Syntax
<!ATTLIST element-name attribute-name
attribute-type #IMPLIED>
DTD Example
<!ATTLIST emergency no. CDATA
#IMPLIED>
Valid XML:
<emergency no.="555-
667788" />
Valid XML:
<emergenc
y/>
Use the #IMPLIED keyword if you don't want to force the author to include an attribute, and you
don't have an option for a default value.
FIXED
Syntax
<!ATTLIST element-name attribute-name
attribute-type #FIXED "value">
DTD Example
<!ATTLIST Client CDATA #FIXED
"RoseIndia">
Valid XML:
<Client
="RoseIndia" />
Invalid XML:
<Client="LotusIn
dia" />
Use the #FIXED keyword when you want an attribute to have a fixed value without allowing the
author to change it. If an author includes another value, the XML parser will return an error.
Enumerated Attribute Values
Syntax
<!ATTLIST element-name attribute-name (en1|
en2|..) default-value>
DTD Example
<!ATTLIST reciept type (check|cash)
"cash">
XML example:
<reciept
type="check" />
or
<reciept
type="cash" />
Use enumerated attribute values when you want the attribute value to be one of a fixed set of
legal values
DTD-Entities
Entities are variables used to define shortcuts to standard text or special characters. Entity
references are references to entities Entities can be declared internally or externally.
Internal Entity Declaration
Syntax
<!ENTITY entity-name
"entity-value">
DTD Example:
<!ENTITY name "Amit">
<!ENTITY company
"RoseIndia">
XML example:
<Profile>&name;&company
;</Profile>
Note: An entity has three parts: an ampersand (&), an entity name, and a semicolon (;).
An External Entity Declaration
Syntax
<!ENTITY entity-name
SYSTEM "URI/URL">
DTD Example:
<!ENTITY name SYSTEM
"http://www.roseindia.net/entities.dtd">
<!ENTITY company SYSTEM
"http://www.roseindia.net/entities.dtd">
XML example:
<Profile>&name;&company
;</Profile>
In this tutorial you will learn how to read and create XML Schemas, why XML Schemas are
more powerful than DTDs, and how to use them in your application.
XML Schema is a W3C Standard. It is an XML-based alternative to DTDs. It describes the
structure of an XML document. The XML Schema language is also referred to as XML Schema
Definition (XSD).
We think that very soon XML Schemas will be used in most Web applications as a
replacement for DTDs. Here are some reasons:
• XML Schemas are extensible to future additions
• XML Schemas are richer and more powerful than DTDs
• XML Schemas are written in XML, supports data types and namespaces.
What is an XML Schema?
XML Schema is used to define the legal building blocks of an XML document, just like a DTD.
An XML Schema defines user-defined integrants like elements, sub-elements and attributes
needed in a xml document. It defines the data types for elements and attributes along with the
occurrence order . It defines whether an element is empty or can include text. It also defines
default and fixed values for elements and attributes
Why Use XML Schemas?
XML Schemas are much more powerful than DTDs.
Features of XML Schemas :
XML Schemas Support Data Types
One of the greatest strengths of XML Schemas is its support for data types. With support for data
types:
• It is easier to describe allowable document content
• It is easier to validate the correctness of data
• It is easier to work with data from a database
• It is easier to define data facets (restrictions on data)
• It is easier to define data patterns (data formats)
• It is easier to convert data between different data types
XML Schemas use XML Syntax
Another great strength about XML Schemas is that they are written in XML. Simple XML
editors are used to edit the Schema files. Even the same XML parsers can be used to parse the
Schema files.
XML Schemas are Extensible
XML Schemas are extensible, because they are written in XML.So a user can reuse a Schema in
other Schemas and can also refer multiple schemas in the same document. He can also create his
own data types derived from the standard types
Well-Formed is not Enough alone
A well-formed XML document is a document that conforms to the XML syntax rules.Even if
documents are well-formed they can still contain errors, and those errors can have serious
consequences.
Think of the following situation: you order 5 gross of laser printers, instead of 5 laser printers.
With XML Schemas, most of these errors can be caught by your validating software.
XML Schemas Secure Reliable Data Communication
When sending data from a sender to a receiver, it is essential that both parts have the same
"expectations" about the content. With XML Schemas, the sender can describe the data in a way
that the receiver will understand. A date like: "03-11-2004" will, in some countries, be
interpreted as 3.November and in other countries as 11.March.However, an XML element with a
data type like this: <datetype="date">2004-03-11</date> ensures a mutual understanding of the
content, because the XML data type "date" requires the format "YYYY-MM-DD".
XML Schema
The following example is a XML Schema file called "E-mail.xsd" that defines the elements of
the XML document above ("E-mail.xml"):
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.roseindia.net"
xmlns="http://www.roseindia.net"
elementFormDefault="qualified">
<xs:element name="E-mail">
<xs:complexType>
<xs:sequence>
<xs:element name="To" type="xs:string"/>
<xs:element name="From" type="xs:string"/>
<xs:element name="Subject" type="xs:string"/>
<xs:element name="Body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
We will discuss the building blocks of this schema latter in this section further.
Add a reference to the above declared XML document
Now this XML document (E-mail.xml) has a reference to above declared XML Schema(E-
mail.xsd)
<?xml version="1.0"?>
<E-mail
xmlns="http://www.roseindia.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema"
xsi:schemaLocation="http://www.roseindia.net/Schema E-
mail.xsd">
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...</Body>
</E-mail>
In the above xml document xmlns declares the XML namespaces (we will discuss
it in the coming segment of current page).
Save E-mail.xml and E-mail.xsd in the same location. Open the file E-mail.xml in a web-
browser. You will see the following :
When a namespace is defined in the start tag of an element, all child elements with the same
prefix are associated with the same namespace. In E-mail.xsd "xs" is the defined namespace in
the start tag. So it prefixes all the child elements with xs eg...
<xs:element name="E-mail">
<xs:complexType>
<xs:sequence>
<xs:element name="To" type="xs:string"/>
<xs:element name="From"
type="xs:string"/>
<xs:element name="Subject"
type="xs:string"/>
<xs:element name="Body"
type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Note that the address used to identify the namespace is not used by the parser to look up
information. The only purpose is to give the namespace a unique name. However, very often
companies use the namespace as a pointer to a real Web page containing information about the
namespace.
Here a Uniform Resource Identifier (URI) is a string of characters which identifies an Internet
Resource.
Default Namespaces : Defining a default namespace for an element saves us from using
prefixes in all the child elements. It has the following syntax:
xmlns="namespaceURI"
We have not included prefixes in all the child element tags( To, From, Subject, Body) in our
following example :
<?xml version="1.0"?>
<E-mail
xmlns="http://www.roseindia.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://www.roseindia.net/Schema
E-mail.xsd">
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...</Body>
</E-mail>
indicates that the elements defined by this schema (E-mail, To, From, Subject, Body.) come from
the "http://www.roseindia.net" namespace.
This fragment:
xmlns="http://www.roseindia.net"
indicates that the default namespace is "http://www.roseindia.net".
This fragment:
elementFormDefault="qualified"
indicates that any elements used by the XML instance document which were declared in this
schema must be a namespace qualified.
Referencing a Schema in an XML Document
This XML document (E-mail.xml) has a reference to an XML Schema (E-mail.xsd).
<?xml version="1.0"?>
<E-mail
xmlns="http://www.roseindia.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema"
xsi:schemaLocation="http://www.roseindia.net/Schema E-
mail.xsd">
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...</Body>
</E-mail>
you can use the schemaLocation attribute. This attribute has two values. The first value is the
namespace to use. The second value is the location of the XML schema to use for that
namespace:
xsi:schemaLocation="http://www.roseindia.net note.xsd"
XML simple element contains only text not even any other elements or attributes.But the text
can be of many different types. It can be among the types included in the XML Schema
definition (boolean, string, date, etc.), or it may be a custom type that a user is free to define.
Even. restrictions (facets) can be added to a data type in order to limit its content.
Defining a Simple Element
The syntax for a simple element is:
<xs:element name="aaa" type="bbb"/>
where aaa is the name of the element and bbb is the data type of the element.
XML Schema has a lot of built-in data types. The most common types are:
• xs:string
• xs:decimal
• xs:integer
• xs:boolean
• xs:date
• xs:time
Example:
Few of XML elements:
<name>Rahul</name>
<age>15</age>
<currentdate>2007-05-
15</currentdate>
Simple elements may have a specified default value OR a fixed specified value .A default
value is automatically assigned to the element when no other value is specified for example to
set the "orange" default value .
<xs:element name="fruit" type="xs:string"
default="orange"/>
Fixed Values for Simple Elements
A fixed value is also automatically assigned to the element, and it cannot further specify
another value.
In the following example the fixed value is "apple":
<xs:element name="fruit" type="xs:string"
fixed="apple"/>
Look at this complex XML element, "employee", which contains only other elements:
<employee>
<firstname>Amit</firstname>
<lastname>Gupta</lastname>
</employee>
In the above described method only "employee" element can use the specified complex type.
Note that the child elements, "firstname" and "lastname", are surrounded by the <sequence>
indicator. This means that the child elements must appear in the same order as they are
declared.
2. "employee" element can have a type attribute refering to the name of the complex type to
use:
<xs:element name="employee" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
Using the method described above, several elements can refer to the same complex type, like
this:
<xs:element name="employee" type="personinfo"/>
<xs:element name="employer" type="personinfo"/>
<xs:element name="teammember" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
XSD Attributes
What is an Attribute?
Simple elements do not contain attributes. If an element has attributes, then it is of a complex
type element. But the attribute itself is always declared as a simple type.
Defining an Attribute?
The syntax for defining an attribute is:
<xs:attribute name="aaa" type="bbb"/>
where aaa is the name of the attribute and bbb specifies the data type of the
attribute.
XML Schema has a lot of built-in data types. The most common types are:
• xs:string
• xs:decimal
• xs:integer
• xs:boolean
• xs:date
• xs:time
Example:
Here is an XML element with an attribute:
<name lang="EN">Rahul</name>
And here is the corresponding attribute definition:
<xs:attribute name="lang" type="xs:string"/>
Attributes are optional by default. To specify that the attribute is required, use the "use" attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>
Restrictions on Content
When an XML element or attribute has a data type defined, it can put restrictions on the
element's or attribute's content. If an XML element is of type "xs:age" and contains a string like
"Hello", the element will not validate. With XML Schemas, user can also add his own
restrictions to XML elements and attributes. These restrictions are called facets
XML Parsers
Here we have listed all the major Java APIs for XML. But we will concentrate most on JAXP
in our coming tutorials.
JAXP: Java API for XML Processing
This API provides a common interface for creating and using the standard
SAX, DOM, and XSLT APIs in Java, independent to vendor's implementation .
This standard defines a mechanism for writing out Java objects as XML
(marshalling) and for creating Java objects from such structures
(unmarshalling).
JAXP doesn't do any kind of processing instead it provides a mechanism to obtain parsed XML
documents employing SAX and DOM parsers . JAXP provides a mechanism to plug-in with
various providers (supporting standard specifications for DOM, SAX and XSLT ). JAXP also
specifies which provider to use.
Overview of the main JAXP API Packages
javax.xml.transfor Defines the XSLT APIs that let's to transform XML into
m other forms.
The SAX API is defined in org.xml.sax package of JAXP-APIs. The "Simple API" for XML
(SAX) is the event-driven, serial-access mechanism that does element-by-element processing.
The API for this level reads and writes XML to a data repository or the Web.
The DOM API is defined in org.w3c.dom package of JAXP-APIs. The DOM API is easier to
use. It provides a tree structure of objects. The DOM API are used to manipulate the hierarchy
of application objects it encapsulates.
The XSLT APIs defined in javax.xml.transform package of JAXP-APIs. The XSLT APIs let
you convert XML data to into other forms.
javax.xml.parsers --Description
Provides classes to process XML documents and supports two types of plugable parsers
ie..SAX and DOM Here are the following classses defined in javax.xml.parsers package:
Defines the API to obtain DOM Document instances
DocumentBuilder
from an XML document.
DOM Level I provided core mechanisms for traversing a tree and adding,
deleting, and updating content.
XSLT 2.0
The SAX Packages: The SAX parser is defined in the following packages.
Package Description
SAXParser
SAXReader
DefaultHandler
ContentHandler
ErrorHandler
DTDHandler
Defines methods you will rarely call. Used while processing a DTD to
recognize and act on declarations for an unparsed entity.
EntityResolver
The resolveEntity method is invoked when the parser needs to identify the
data referenced by a URI.
The diagram here shows the JAXP APIs to process xml document using the DOM parser:
javax.xml.parsers.DocumentBuilderFactory class creates the instance of
DocumentBuilder. Through DocumentBuilder it produces a Document (a DOM) that
conforms to the DOM specification. The System property determines , the builder at the run
time using javax.xml.parsers.DocumentBuilderFactory (it selects the factory implementations
to produce the builder). The platform's default value ie..system property can be overridden
from the command line.
This Example describes a method to create a new DOM tree .Methods which are used for
making a new DOM parse tree are described below :-
Element root = doc.createElement("places"):-it is a method to Create an Element node.
doc.appendChild(root):-This method adds a node after the last child node of the specified
element root.
Element root = doc.getDocumentElement():-allows direct access to the root of the DOM
document.
Xml code for the program generated is:-
<?xml version="1.0"
encoding="UTF-8"?>
<!--
Document :
Document6.xml
Created on : 10 July,
2008, 5:20 PM
Author : girish
Description:
Purpose of the
document follows.
-->
<root>
</root>
Parsetree.java:-
/*
* @Program that Creates a New DOM Parse Tree
* Parsetree.java
* Author:-RoseIndia Team
* Date:-10-Jun-2008
*/
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
}
}
This Example shows you how to Create an Element node ,Comment node ,Attribute node,
Processing node and CDATA section node in a DOM document. JAXP (Java API for XML
Processing) is an interface which provides parsing of xml documents. Here the Document
BuilderFactory is used to create new DOM parsers. These are some of the methods used in code
given below for adding attribute:-
Element root = doc.createElement("Company"):-This method creates an element node ,Here
Company specifies the name for the element node.
doc.appendChild(root):-This method adds a node after the last child node of the specified
element node.
Comment node = doc.createComment("Comment for company"):-This method creates an
Comment node ,Here "Comment for company" specifies the name for the Comment node.
CDATASection cdata = doc.createCDATASection("Roseindia <, >, .net rohini"):- This
method creates a CDATASection node. Here string "Roseindia <, >, .net rohini" specifies the
data for the node
Xml code for the program generated is:-
<?xml version="1.0"
encoding="UTF-8"?>
<root></root>
CreatesElementnode.java:-
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
root.getFirstChild().getNextSibling());
ProcessingInstruction pi =
doc.createProcessingInstruction("Roseindia", "Rohini");
root.appendChild(pi);
System.out.println("ProcessingInstruction node created is: " +
root.getLastChild());
}
}
This Example shows you how to adds an attribute in a DOM document. JAXP (Java API for
XML Processing) is an interface which provides parsing of xml documents. Here the
Document BuilderFactory is used to create new DOM parsers. There are some of the methods
used in code given below for adding attribute:-
getDocumentElement():- allows direct access to the root node of the document.
root.getAttribute("Id"):-allows to retrieve attributes on Id.
root.setAttribute("Id", "05MC34"):-allows to set o5Mc34 on the Id
Xml code for the program generated is:-
<?xml version="1.0" encoding="UTF-
8"?>
<Author Type='Bible' Id='Rose-78'
Issue='1995'>
</Author>
Addingattribute.java :-
/*
* @Program that Adds an Attribute to an Element
* Addingattribute.java
* Author:-RoseIndia Team
* Date:-09-Jun-2008
*/
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
This Example shows you how to Load Properties from the XML file via a DOM document.
JAXP (Java API for XML Processing) is an interface which provides parsing of xml
documents.Javax.xml.parsers is imported to provide classes for the processing of XML
Documents. Here the Document BuilderFactory is used to create new DOM parsers. Some of the
methods used for reading XML from a file are described below :-
File f = new File("Document2.xml"):-Creating File from where properties are to be loaded.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance():-Declaring
DocumentBuilderFactory to create new DOm parsers.
Element root = doc.getDocumentElement():-By this method we can have direct access to the root
of the DOM Document.
NodeList list = doc.getElementsByTagName("Employee"):-NodeList is an interface that
provides an ordered collection of nodes.We can access nodes from the Nodelist by their index
number.
NodeList nodelist = element.getElementsByTagName("name"):-This method returns a list of
element with a given tagname i.e ("name").
Xml code for the program generated is:-
readxmlfromafile.java
/*
* @Program to load properties from XML file.
* readxmlfromafile.java
* Author:-RoseIndia Team
* Date:-10-Jun-2008
*/
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
Name :
Roseindia.net
Name : newsTrack
Name : Girish
Tewari
XMLtoXSL.java
/*
* @Program that Transforms an XML Fil
e with XSL
* XMLtoXSL.java
* Author:-RoseIndia Team
* Date:-23-July-2008
*/
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
DOM4J
This Example shows you how to Read XML Data via a Stream in a DOM document. JAXP (Java
API for XML Processing) is an interface which provides parsing of xml documents. Here the
Document BuilderFactory is used to create new DOM parsers.There are some of the methods
used in code given below for Reading XML Data:-
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance():-This
method Creates a DocumentBuilderFactory .DocumentBuilderFactory is a Class that enables
application to obtain parser for building DOM trees from XML Document
DocumentBuilder builder = Factory.newDocumentBuilder():-This method creates a
DocumentBuilder object with the help of a DocumentBuilderFactory.
transformer.transform(source, result):-This method process the source tree to the output result.
Xml code for the program generated is:-
<?xml version="1.0" encoding="UTF-
8"?>
<Company>
<Employee Id="Rose-2345">
<CompanyName>RoseIndia.net</Co
mpanyName>
<City>Haldwani</City>>
<name>Girish Tewari</name>
<Phoneno>1234567890</Phoneno>
<Doj>May 2008</Doj>
</Employee>
<Employee Id="Rose-2346">
<CompanyName>RoseIndia.net</Co
mpanyName>
<City>Lucknow</City>
<name>Mahendra
Singh</name>
<Phoneno>123652314</Phoneno>
<Doj>May 2008</Doj>
</Employee>>
</Company>
ReadingXmlDataFromStream.java
/*
* @Program To Read XML Data from a Stream.
* ReadingXmlDataFromStream.java
* Author:-RoseIndia Team
* Date:-17-July-2008
*/
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
<CompanyName>RoseIndia.net</Compa
nyName>
<City>Haldwani</City>>
<name>Girish Tewari</name>
<Phoneno>1234567890</Phoneno>
<Doj>May 2008</Doj>
</Employee>
<Employee Id="Rose-2346">
<CompanyName>RoseIndia.net</Compa
nyName>
<City>Lucknow</City>
<name>Mahendra Singh</name>
<Phoneno>123652314</Phoneno>
<Doj>May 2008</Doj>
</Employee>>
</Company>