Introduction to Java XML Parser
The following article provides an outline for Java XML Parser. XML parsing for Java is a stand-alone XML component that parses an XML document (and, in certain cases, a standalone DTD or XML Schema) so that it may be processed by a user program. It may also include an XSL Transformation (XSLT) Processor for XML data transformation using XSL stylesheets. We may simply convert XML documents from XML to XML, XML to HTML, or nearly any other text-based format with the XSLT Processor.
Syntax of Java XML Parser
The general parsing format is given as:
1. Using DOM
DOMParser parser = new DOMParser();
2. Using SAX
Parser parser = new SAXParser();
XML (Extensible Markup Language) is a markup language that specifies a set of rules for encoding texts. To parse and process XML documents, Java provides several libraries. The essential functionality to read and change an XML file is provided by Java xml parser examples.
How does Java XML Parser Work?
When it comes to parsing XML documents, Java has a lot of possibilities.
The following are some of the most widely used Java XML parsers:
- DOM
- SAX
- JAXB
- Streaming API for XML (Stax)
JAXB and Stax are new versions of Java. Stax parser uses a cursor and even iterator API for parsing XML documents. It takes two interfaces Event Reader and Event Writer and the application loop over the whole document for the next waiting Event.API type of Stax is pulled and streaming with no Xpath compatibility. Pull parsing allows the client to control the application thread and call parser methods as needed. Push processing, on the other hand, allows the parser to control the application thread and the client to take only invocations from the parser. The abstract base class is XMLParser. The parse () method of an instantiated parser is used to read an XML document.
Java XML Parser Working:
- The XML Parser for Java receives an XML document as input.
- The XML document is parsed using the DOM or SAX parser interface.
- The application receives the parsed XML and does the work further.
SAX Parser
SAX stands for Simple API for XML, and the Push Parser is a stream-oriented XML Parser. The primary goal is to read the XML file and create an event to perform a call function or to use call-back routines. This parser works in the same way that the Java Event handler does. It’s required to register handlers to parse the page and handle various events.
In order to offer the following call-backs, the SAX parser extends the Default Handler class:
- startElement: When a start tag is found, this event is triggered.
- endElement: When an end tag is met, this event is triggered.
- characters: When some text data is found, this event is triggered.
Examples of Java XML Parser
Given below are the examples mentioned:
Example #1
Java DOM Parser.
Code:
Read.java:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class Read {
private static final String FILENAME = "D:\\parser\\amaz.xml";
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(FILENAME));
doc.getDocumentElement().normalize();
System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
System.out.println("------");
// get <staff>
NodeList list = doc.getElementsByTagName("amz");
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String id = element.getAttribute("id");
String office = element.getElementsByTagName("office").item(0).getTextContent();
String location = element.getElementsByTagName("location").item(0).getTextContent();
String Country = element.getElementsByTagName("Country").item(0).getTextContent();
NodeList companyNodeList = element.getElementsByTagName("company");
String company = companyNodeList.item(0).getTextContent();
String growth = companyNodeList.item(0).getAttributes().getNamedItem("growth").getTextContent();
System.out.println("Current Element :" + node.getNodeName());
System.out.println("Staff Id : " + id);
System.out.println("office : " + office);
System.out.println("location : " + location);
System.out.println("Country : " +Country);
System.out.printf("company [growth] : %,.2f [%s]%n%n", Float.parseFloat(company), growth);
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
amaz.xml:
This XML file contains xml attributes also along with xml elements.
<?xml version="1.0"?>
<company>
<staff id="1001">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary currency="USD">100000</salary>
</staff>
<staff id="2001">
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary currency="INR">200000</salary>
</staff>
</company>
Explanation:
- In the above code, first, import the dom parser packages into the application.
- Next, the DocumentBuilder object will be created.XML file is taken to the document object. Finally, parse the XML file and save it in the document class.
Output:
Example #2
Java SAX Parser.
Code:
Read.java:
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 Read
{
public static void main(String args[])
{
try
{
SAXParserFactory f = SAXParserFactory.newInstance();
SAXParser saxP= f.newSAXParser();
DefaultHandler hdl = new DefaultHandler()
{
boolean fid = false;
boolean fname = false;
boolean fproduct = false;
boolean discount = false;
boolean dataware = false;
public void startElement( String sg, String pp,String q, Attributes a) throws SAXException
{
System.out.println("First Node :" + q);
if(q.equalsIgnoreCase("FID"))
{
fid=true;
}
if (q.equalsIgnoreCase("FNAME"))
{
fname = true;
}
if (q.equalsIgnoreCase("FPRODUCT"))
{
fproduct = true;
}
if (q.equalsIgnoreCase("DISCOUNT"))
{
discount = true;
}
if (q.equalsIgnoreCase("DATAWARE"))
{
dataware = true;
}
}
public void endElement(String u, String l, String qNa) throws SAXException
{
System.out.println("Final Node:" + qNa);
}
public void characters(char chr[], int st, int len) throws SAXException
{
if (fid)
{
System.out.println("FID : " + new String(chr, st, len));
fid = false;
}
if (fname)
{
System.out.println("Shop details: " + new String(chr, st, len));
sname = false;
}
if (fproduct)
{
System.out.println("Remaining Product: " + new String(chr, st, len));
fproduct = false;
}
if (discount)
{
System.out.println("discount given: " + new String(chr, st, len));
discount = false;
}
if (dataware)
{
System.out.println("location : " + new String(chr, st, len));
dataware= false;
}
}
};
saxParser.parse("D:\\parser\\amaz.xml", handler);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
amaz.xml:
<?xml version="1.0"?>
<onlineshop>
<flipkart>
<fid>301</fid>
<fname> ethinic</fname>
<fproduct> kurtas</fproduct>
<discount> 10</discount>
<dataware> bangalore</dataware>
</flipkart>
<flipkart>
<fid>401</fid>
<fname> partywear</fname>
<fproduct> saree</fproduct>
<discount> 20</discount>
<dataware> mumbai</dataware>
</flipkart>
<flipkart>
<fid>501</fid>
<fname> kids</fname>
<fproduct> t-shirts</fproduct>
<discount> 12</discount>
<dataware> Uttarpradesh</dataware>
</flipkart>
</onlineshop>
Explanation:
- The above code implements a SAX parser that takes a new instance from the Flipkart shopping file. It parses node by node.
Output:
Conclusion
Java XML parser is to read and validate XML documents. In the above article, we have gone through different types of parsers with an example. SAX parsers are faster than a DOM parsers.
Recommended Articles
This is a guide to Java XML Parser. Here we discuss the introduction, how does Java XML parser work? SAX parser and examples respectively. You may also have a look at the following articles to learn more –
41 Online Courses | 29 Hands-on Projects | 305+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses