JAXP
JAXP
JAXP
Introduction
Any application that uses an XML document must parse its
information in order to access the contents of the document.
There are parsers available that are designed to parse an
XML document and are accessible through an Application
Program Interface (API)
The parser API consists of Java classes that provide easy
access to elements of an XML document
An XML document can be created, read, and manipulated
using Java Application Program Interfaces that are especially
designed for use with an XML document.
Overview of JAXP
JAXP : Java API for XML Processing
Provides a common interface for creating and using the
standard SAX, DOM, and XSLT APIs in Java.
All JAXP packages are included standard in JDK 1.4+.
The key packages are:
javax.xml.parsers:The main JAXP APIs, which provide a
common interface for various SAX and DOM parsers.
org.w3c.dom:Defines the Document class (a DOM), as well as
classes for all of the components of a DOM.
Contd..
org.xml.sax: Defines the basic SAX APIs.
javax.xml.transform: Defines the XSLT APIs that let
you transform XML into other forms.
JAXP XML Parsers
javax.xml.parsers: It defines abstract classes
DocumentBuilder (for DOM)
SAXParser (for SAX)
It also defines factory classes
DocumentBuilderFactory
SAXParserFactory.
By default, these give you the “reference implementation” of
DocumentBuilder and SAXParser, but they are intended to be
vendor-neutral factory classes, so that you could swap in a
different implementation if you preferred.
SAX vs. DOM
SAX = Simple API for XML DOM = Document Object Model
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class Book {
public static void main(String args[ ]){
try{
DocumentBuilderFactory db=DocumentBuilderFactory.newInstance();
DocumentBuilder d=db.newDocumentBuilder(); //parser
String book1="book.xml";
Document doc=d.parse(new File(book1));
Element e=doc.getDocumentElement(); //returns the root element
NodeList book=e.getElementsByTagName("chapter");
for(int i=0;i<book.getLength();i++){
Element el = (Element) book.item(i);
System.out.println("Element : "+el.getNodeName());
NodeList nl=el.getElementsByTagName("chapNum");
Text t1=(Text) nl.item(0).getFirstChild();
System.out.println("Value of chapNum: "+t1.getData());
NodeList nl1=el.getElementsByTagName("chapTitle");
Text t2=(Text) nl1.item(0).getFirstChild();
System.out.println("Value of chapTitle: "+t2.getData());
}
}catch(Exception e){System.out.println("Error Parsing "+ e.getMessage());}
}
}
Input
Output <book>
Element : chapter
<chapter>
Value of chapNum : One
<chapNum>One</chapNum>
Value of chapTitle : XML
<chapTitle>XML</chapTitle>
Element : chapter
Value of chapNum : Two </chapter>