
- Home
- Binder
- DatatypeConverter
- JAXB
- JAXBContext
- JAXBElement
- JAXBElement.GlobalScope
- JAXBIntrospector
- Marshaller.Listener
- SchemaOutputResolver
- Unmarshaller.Listener
- Javax.xml.bind.util classes
- JAXBResult
- JAXBSource
- ValidationEventCollector
- Javax.xml.parsers classes
- DocumentBuilder
- DocumentBuilderFactory
- SAXParser
- SAXParserFactory
- Javax.xml.soap classes
- AttachmentPart
- MessageFactory
- MimeHeader
- MimeHeaders
- SAAJMetaFactory
- SOAPConnection
- SOAPConnectionFactory
- SOAPFactory
- SOAPMessage
- SOAPPart
- Javax.xml.validation classes
- Schema
- SchemaFactory
- TypeInfoProvider
- Validator
- ValidatorHandler
- Javax.xml.xpath classes
- XPathConstants
- XPathFactory
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources

Javax.xml package Tutorial
Java - javax.xml Package
The javax.xml package is a standard package of Java SDK. It contains classes for XML processing. This package is very useful as it provides DOM Parser, SAX parser, Streaming API for XML (StAX), validating XML and lot more. This reference will take you through simple and practical methods available in javax.xml package.
Importing javax.xml Package
JAXB library provides javax package and javax can be imported using following syntax:
import javax.xml.bind.*;
Here we've used * operator to import all classes from java.xml package and now any class can be used in the program. In case of specific class, for example InputStream, we can import a class using following syntax:
import javax.xml.bind.Binder;
Why javax.xml Package is used in Java Programs
Javax.xml package classes contains various XML parsers and other utility classes. Following list shows some of the categories of classes of javax.xml package.
XPath − Classes for XML navigation, parsing and search operations.
DOM − Classes for DOM Based parsing of XML.
SAX − Classes for Stream Based parsing of XML.
SOAP − Classes for SOAP based XML message handling.
XML Validation − Classes for XML, XSD validations.
Important classes in javax.xml Package
Following is the list of important classes in java.io.package:
- Binder − The Binder class enable synchronization between XML infoset nodes and JAXB objects representing same XML document.
- DatatypeConverter − The DatatypeConverter class makes it easier to write parse and print methods.These methods are invoked by custom parse and print methods.
- JAXB − The JAXB class defines convenience methods for common, simple use of JAXB.
- JAXBContext − The JAXBContext class provides the client's entry point to the JAXB API.This class provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations: unmarshal, marshal and validate.
- JAXBElement − The JAXBElement class is the JAXB representation of an Xml Element.This class represents information about an Xml Element from both the element declaration within a schema and the element instance value within an xml document.
- JAXBElement.GlobalScope − The JAXBElement.GlobalScope class designates global scope for an xml element.
- JAXBIntrospector − The JAXBIntrospector class provides access to JAXB xml binding data for a JAXB object.The intent of this class is to just conceptualize how a JAXB application developer can access xml binding information, independent if binding model is java to schema or schema to java.
- Marshaller.Listener − The Marshaller.Listener class registers an instance of an implementation of this class with a Marshaller to externally listen for marshal events.This class enables pre and post processing of each marshalled object.
- SchemaOutputResolver − The SchemaOutputResolver class controls where a JAXB implementation puts the generates schema files.This is a class, not an interface so as to allow future versions to evolve without breaking the compatibility.
- Unmarshaller.Listener − The Unmarshaller.Listener class registers an instance of an implementation of this class with Unmarshaller to externally listen for unmarshal events.This class enables pre and post processing of an instance of a JAXB mapped class as XML data is unmarshalled into it.
- JAXBResult − The JAXBResult class utility is useful to combine JAXB with other Java/XML technologies.This is the JAXP Result implementation that unmarshals a JAXB object.
- JAXBSource − The JAXBSource class utility is useful to combine JAXB with other Java/XML technologies.This is the JAXP Source implementation that marshals a JAXB-generated object.
- ValidationEventCollector − The ValidationEventCollector class can be used by creating a new instance and pass it to the setEventHandler method of the Validator, Unmarshaller, Marshaller class. After the call to validate or unmarshal completes, call the getEvents method to retrieve all the reported errors and warnings.
- DocumentBuilder − The DocumentBuilder class defines the API to obtain DOM Document instances from an XML document.
- DocumentBuilderFactory − The DocumentBuilderFactory class defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
- SAXParser − The SAXParser class defines the API that wraps an XMLReader implementation class.
- SAXParserFactory − The SAXParserFactory class defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.
- AttachmentPart − The AttachmentPart class is a single attachment to a SOAPMessage object.
- MessageFactory − The MessageFactory class is a factory for creating SOAPMessage objects.
- MimeHeader − The MimeHeader class object stores a MIME header name and its value. One or more MimeHeader objects may be contained in a MimeHeaders object.
- MimeHeaders − The MimeHeaders class returns the value of this MimeHeader object.
- SAAJMetaFactory − The javax.xml.soap.SAAJMetaFactory class is the access point for the implementation classes of the factories defined in the SAAJ API.
- SOAPConnection − The SOAPConnection class is a point-to-point connection that a client can use for sending messages directly to a remote party (represented by a URL, for example).
- SOAPConnectionFactory − The javax.xml.soap.SOAPConnectionFactory class is a factory for creating SOAPConnection objects. Implementation of this class is optional.
- SOAPFactory − The SOAPFactory class is a factory for creating various objects that exist in the SOAP XML tree.SOAPFactory can be used to create XML fragments that will eventually end up in the SOAP part.
- SOAPMessage − The SOAPMessage class is the root class for all SOAP messages.A SOAP message is an XML document or a MIME message whose first body part is an XML/SOAP document.
- SOAPPart − The SOAPPart class is the container for the SOAP-specific portion of a SOAPMessage object.
- Schema − The Schema class is an Immutable in-memory representation of grammar.
- SchemaFactory − The SchemaFactory class is a factory that creates Schema objects.
- TypeInfoProvider − The TypeInfoProvider class provides access to the type information determined by ValidatorHandler.
- Validator − The Validator class is a processor that checks an XML document against Schema.A validator object is not thread-safe and not reentrant.
- ValidatorHandler − The ValidatorHandler class is a streaming validator that works on SAX stream.A ValidatorHandler object is not thread-safe and not reentrant.
- XPathConstants − The XPathConstants class are XPath constants.
- XPathFactory − The XPathFactory class instance can be used to create XPath objects.
Examples of javax.xml Package
Practice the following examples to learn the concept and usage of javax.xml package clasess.
Example of javax.xml.bind.JAXB
The following program illustrates several of the methods supported by JAXB −
package com.tutorialspoint; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.*; import javax.xml.bind.JAXB; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; @XmlRootElement class Student{ String name; int age; int id; public String getName(){ return name; } @XmlElement public void setName(String name){ this.name = name; } public int getAge(){ return age; } @XmlElement public void setAge(int age){ this.age = age; } public int getId(){ return id; } @XmlAttribute public void setId(int id){ this.id = id; } } public class JAXBDemo { public static void main(String[] args) { // create student object Student st = new Student(); st.setAge(13); st.setName("Rehman"); try { // create new file object File f = new File("Student.xml"); // saves student object to the file JAXB.marshal(st, f); // create document object from the student.xml DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse("Student.xml"); // print the marshalled object to the stdout TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(document), new StreamResult(System.out)); }catch(Exception ex) { ex.printStackTrace(); } } }
Output
Before we proceed for compilation, we need to make sure that that we download JAXB2.xxx.jar and put it in our CLASSPATH. Once setup is ready, let us compile and run the above program, this will produce the following result −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <student id = "10"> <age>13</age> <name>Rehman</name> </student>
Example of Javax.xml.parsers.SAXParser
The following program illustrates several of the methods supported by SAXParser −
package com.tutorialspoint; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class SaxParserDemo { public static void main(String[] args) { // create a new SAXParserFactory SAXParserFactory factory = SAXParserFactory.newInstance(); try { // get a new SAXParser SAXParser parser = factory.newSAXParser(); // get the XMLReader object System.out.println("" + parser.getXMLReader()); } catch (Exception ex) { ex.printStackTrace(); } } }
Output
Let us compile and run the above program, this will produce the following result −
com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser@6abf2d5e
Example of Javax.xml.parsers.DocumentBuilder
The following program illustrates several of the methods supported by DocumentBuilder −
For our examples to work, a xml file named Student.xml is needed in our CLASSPATH. The contents of this XML are the following −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <student id = "10"> <age>12</age> <name>Malik</name> </student>
The following example shows the usage of Javax.xml.parsers.DocumentBuilder.parse() method.
package com.tutorialspoint; 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 DocumentBuilderDemo { public static void main(String[] args) { // create a new DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { // use the factory to create a documentbuilder DocumentBuilder builder = factory.newDocumentBuilder(); // create a new document from file File file = new File("Student.xml"); Document doc = builder.parse(file); // get the first element Element element = doc.getDocumentElement(); // get all child nodes NodeList nodes = element.getChildNodes(); // print the text content of each child for (int i = 0; i < nodes.getLength(); i++) { System.out.println("" + nodes.item(i).getTextContent()); } } catch (Exception ex) { ex.printStackTrace(); } } }
If we compile the code and execute it, this will produce the following result −
12 Malik
When javax.xml Package is Used?
Whenever we need to perform XML related operations, we can rely on xml classes present in javax.xml package. This reference has been prepared for the beginners to help them understand the basic functionality related to all the methods available in Javax.xml package.
Prerequisites
Before you start doing practice with various types of examples given in this reference, I'm making an assumption that you are already aware of basic Java Programming.