Read XML file in Java using SAX parser
SAX stands for Simple API for XML. It is an event based parsing and you need to create your own handler Class for handling the events (like StartDocument, EndDocument, StartElement, EndElement, etc) whenever SAX parser pareses the xml document.
When to use SAX Parser ?
- You should use SAX parser in case of shallow XML documents, documents that are not deeply nested.
- You want to process the XML document in a linear fashion.
Below example shows how to read a XML file in Java using SAX parser
XML file that you want to parse: employees.xml
<?xml version = "1.0"?> <employees> <employee id="123"> <firstname>Mohit</firstname> <lastname>Bisht</lastname> </employee> <employee id="124"> <firstname>Samit</firstname> <lastname>Ahlawat</lastname> </employee> <employee id="125"> <firstname>Vikram</firstname> <lastname>Raheja</lastname> </employee> </employees>
// SAX Parser import java.io.File; 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; // SAX event handler class EmployeeHandler extends DefaultHandler { boolean id = false; boolean firstname = false; boolean lastname = false; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("employee")) { String id = attributes.getValue("id"); System.out.println("id : " + id); } else if (qName.equalsIgnoreCase("firstname")) { firstname = true; } else if (qName.equalsIgnoreCase("lastname")) { lastname = true; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("student")) { System.out.println("End Element :" + qName); } } @Override public void characters(char ch[], int start, int length) throws SAXException { if (firstname) { System.out.println("First Name : " + new String(ch, start, length)); firstname = false; } if (lastname) { System.out.println("Last Name : " + new String(ch, start, length)); lastname = false; } } } public class TestSAXParser { public static void main(String[] args) { try { File inputFile = new File("C://employees.xml"); SAXParserFactory saxParserFactory = SAXParserFactory .newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); EmployeeHandler handler = new EmployeeHandler() ; saxParser.parse(inputFile, handler); } catch (Exception e) { e.printStackTrace(); } } }
Output :
id : 123 First Name : Mohit Last Name : Bisht id : 124 First Name : Samit Last Name : Ahlawat id : 125 First Name : Vikram Last Name : Raheja
Comments on above approach: