{"id":3677,"date":"2020-06-09T19:28:20","date_gmt":"2020-06-09T13:58:20","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=3677"},"modified":"2025-02-07T02:40:59","modified_gmt":"2025-02-07T07:40:59","slug":"how-to-parse-xml-using-sax-dom","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/how-to-parse-xml-using-sax-dom\/","title":{"rendered":"How to Parse XML using SAX\/DOM?"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p>In the world of Java programming, working with structured data is crucial, especially when dealing with XML files. How to Parse XML using SAX\/DOM? XML (Extensible Markup Language) is widely used in data storage, configuration files, and web services. Parsing XML efficiently is an essential skill for <a href=\"https:\/\/www.h2kinfosys.com\/courses\/java-online-training-course-details\/\">Java Full Stack Developers<\/a>.<\/p>\n\n\n\n<p>When working with Parse XML in Java, two primary parsing techniques are SAX (Simple API for XML) and DOM (Document Object Model). Each method has its use cases and benefits, making it important to understand when and how to use them effectively.<\/p>\n\n\n\n<p>This blog will guide you through XML parsing using SAX and DOM, providing in-depth explanations, real-world applications, and hands-on examples. Whether you are a beginner or an advanced Java developer, mastering XML parsing will enhance your Java Full Stack Developer skills.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding XML Parsing in Java<\/h2>\n\n\n\n<p>XML parsing refers to the process of reading Parse XML data and extracting meaningful information from it. In <a href=\"https:\/\/www.h2kinfosys.com\/blog\/tag\/java\/\" data-type=\"post_tag\" data-id=\"58\">Java<\/a>, we primarily use two approaches:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>SAX (Simple API for XML)<\/strong> \u2013 An event-driven, sequential parsing method that is memory-efficient.<\/li>\n\n\n\n<li><strong>DOM (Document Object Model)<\/strong> \u2013 A tree-based parsing method that loads the entire XML structure into memory for easy manipulation.<\/li>\n<\/ul>\n\n\n\n<p>Each approach has its advantages and limitations, which we will explore in detail.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>DOM Parser:<\/strong><\/h2>\n\n\n\n<p>DOM (Document Object Model) provides an interface to update the style, structure, and contents of an XML document. DOM should be used when you want to have knowledge about the structure of the XML document, move parts of an XML document, and want to use the information more than once. After parsing the XML document with the help of DOM parser, you get a tree-like structure that contains all the elements of a document.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>DOM Interfaces:<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Node: It is the base datatype of the document.<\/li>\n\n\n\n<li>Element: The objects in the document are Elements.<\/li>\n\n\n\n<li>Text: The content of an element.<\/li>\n\n\n\n<li>Attr: Represents the attribute of an element.<\/li>\n\n\n\n<li>Document: It refers to the entire Parse XML document.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>DOM Methods:<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Document.getDocumentElement() \u2013 It returns the root element of the document.<\/li>\n\n\n\n<li>Node.getFirstChild() \u2212 It returns the first child of a given Node.<\/li>\n\n\n\n<li>Node.getLastChild() \u2212 It returns the last child of a given Node.<\/li>\n\n\n\n<li>Node.getNextSibling() \u2212 It returns the next sibling of a given Node.<\/li>\n\n\n\n<li>Node.getPreviousSibling() \u2212 It returns the previous sibling of a given Node.<\/li>\n\n\n\n<li>Node.getAttrib<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>When to Use DOM?<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>When working with smaller XML files.<\/li>\n\n\n\n<li>When random access and data modification are required.<\/li>\n\n\n\n<li>When the document structure needs to be retained in memory for multiple operations.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Steps to use DOM:<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Import the XML-related packages:\n<ul class=\"wp-block-list\">\n<li>import org.w3c.dom.*;<\/li>\n\n\n\n<li>import javax.xml.parsers.*;<\/li>\n\n\n\n<li>import java.io.*;<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Create a document builder:\n<ul class=\"wp-block-list\">\n<li>DocumentBuilderFactory factory =<\/li>\n\n\n\n<li>DocumentBuilderFactory.newInstance();<\/li>\n\n\n\n<li>DocumentBuilder builder = factory.newDocumentBuilder();<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Create a document from a file:\n<ul class=\"wp-block-list\">\n<li>StringBuilder xmlStringBuilder = new StringBuilder();<\/li>\n\n\n\n<li>xmlStringBuilder.append(&#8220;&lt;?xml version=&#8221;1.0&#8243;?&gt; &lt;class&gt; &lt;\/class&gt;&#8221;);<\/li>\n\n\n\n<li>ByteArrayInputStream input = new ByteArrayInputStream( xmlStringBuilder.toString().getBytes(&#8220;UTF-8&#8221;));<\/li>\n\n\n\n<li>Document doc = builder.parse(input);<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Extract the root element:\n<ul class=\"wp-block-list\">\n<li>Element root = document.getDocumentElement();<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Examine the attributes:\n<ul class=\"wp-block-list\">\n<li>getAttribute(&#8220;attributeName&#8221;);<\/li>\n\n\n\n<li>getAttributes();<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Examine the sub elements:\n<ul class=\"wp-block-list\">\n<li>getElementsByTagName(&#8220;subelementName&#8221;);<\/li>\n\n\n\n<li>getChildNodes();<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>XML File<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;stocks&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;stock&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;symbol&gt;Citibank&lt;\/symbol&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;price&gt;100&lt;\/price&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;quantity&gt;1000&lt;\/quantity&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/stock&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;stock&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;symbol&gt;Axis bank&lt;\/symbol&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;price&gt;90&lt;\/price&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;quantity&gt;2000&lt;\/quantity&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/stock&gt;\n&lt;\/stocks&gt;<\/code><\/pre>\n\n\n\n<ol start=\"2\" class=\"wp-block-list\">\n<li>JAVA File:<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.File;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\n\npublic class DOMExampleJava {\n\npublic static void main(String args&#91;]) {\ntry {\n\nFile stocks = new File(\"Stocks.xml\");\nDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\nDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\nDocument doc = dBuilder.parse(stocks);\ndoc.getDocumentElement().normalize();\n\nSystem.out.println(\"root of xml file\" + doc.getDocumentElement().getNodeName());\nNodeList nodes = doc.getElementsByTagName(\"stock\");\nSystem.out.println(\"==========================\");\n\nfor (int k = 0; k &lt; nodes.getLength(); k++) {\nNode node = nodes.item(k);\n\nif (node.getNodeType() == Node.ELEMENT_NODE) {\nElement element = (Element) node;\nSystem.out.println(\"Stock Symbol: \" + getValue(\"symbol\", element));\nSystem.out.println(\"Stock Price: \" + getValue(\"price\", element));\nSystem.out.println(\"Stock Quantity: \" + getValue(\"quantity\", element));\n}\n}\n} catch (Exception ex) {\nex.printStackTrace();\n}\n}\n\nprivate static String getValue(String tag, Element element) {\nNodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();\nNode node = (Node) nodes.item(0);\nreturn node.getNodeValue();\n}\n}<\/code><\/pre>\n\n\n\n<p><strong><em>OUTPUT:<\/em><\/strong><\/p>\n\n\n\n<p>root of xml file stocks<\/p>\n\n\n\n<p><em>==========================<br>Stock Symbol: Citibank<br>Stock Price: 100<br>Stock Quantity: 1000<br>Stock Symbol: Axis bank<br>Stock Price: 90<br>Stock Quantity: 2000<\/em><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Key Takeaways from DOM Parsing<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It loads the entire Parse XML document into memory.<\/li>\n\n\n\n<li>It allows for easy manipulation and traversal of data.<\/li>\n\n\n\n<li>It consumes more memory compared to SAX, making it inefficient for large files.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>SAX Parser:<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Understanding SAX Parser<\/strong><\/h3>\n\n\n\n<p>SAX is an event-driven parser, which means it does not load the entire XML into memory. Instead, it reads the document sequentially and <a href=\"https:\/\/en.wikipedia.org\/wiki\/Trigger\" rel=\"nofollow noopener\" target=\"_blank\">Triggers Events<\/a> like <strong>startElement(), characters(), and endElement()<\/strong> to handle Parse XML nodes. This makes it a memory-efficient solution for large XML files.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Advantages of SAX Parser<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Efficient Memory Usage:<\/strong> Suitable for parsing large Parse XML files.<\/li>\n\n\n\n<li><strong>Faster Execution:<\/strong> Reads Parse XML sequentially, making it faster than DOM.<\/li>\n\n\n\n<li><strong>Event-Driven Model:<\/strong> Processes Parse XML elements as they appear.<\/li>\n<\/ul>\n\n\n\n<p>SAX (Simple API for Parse XML) is based on event-based triggers. It does not create a tree as we do in DOM. It is faster and takes less memory. You can use SAX Parser when you need to parse the document in a linear manner from top to bottom.<\/p>\n\n\n\n<p><strong><em>Example:<\/em><\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. <strong>XML File:<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;users&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;user id=\"100\"&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;firstname&gt;Tom&lt;\/firstname&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;lastname&gt;Hanks&lt;\/lastname&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/user&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;user id=\"101\"&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;firstname&gt;Lokesh&lt;\/firstname&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;lastname&gt;Gupta&lt;\/lastname&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/user&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;user id=\"102\"&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;firstname&gt;HowToDo&lt;\/firstname&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;lastname&gt;InJava&lt;\/lastname&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/user&gt;\n&lt;\/users&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. Model Class<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class User\n{\n&nbsp;&nbsp;&nbsp;&nbsp;private int id;\n&nbsp;&nbsp;&nbsp;&nbsp;private String firstName;\n&nbsp;&nbsp;&nbsp;&nbsp;private String lastName;\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;public int getId() {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return id;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;public void setId(int id) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.id = id;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;public String getFirstName() {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return firstName;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;public void setFirstName(String firstName) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.firstName = firstName;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;public String getLastName() {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return lastName;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;public void setLastName(String lastName) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.lastName = lastName;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;@Override\n&nbsp;&nbsp;&nbsp;&nbsp;public String toString() {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return this.id + \":\" + this.firstName +&nbsp; \":\" +this.lastName ;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3. DOM Parser code in JAVA:<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.ArrayList;\nimport java.util.Stack;\n&nbsp;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.helpers.DefaultHandler;\n&nbsp;\npublic class UserParserHandler extends DefaultHandler\n{\n&nbsp;&nbsp;&nbsp;&nbsp;private ArrayList userList = new ArrayList();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;private Stack elementStack = new Stack();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;private Stack objectStack = new Stack();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;public void startDocument() throws SAXException\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;public void endDocument() throws SAXException\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.elementStack.push(qName);\n&nbsp;\n&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (\"user\".equals(qName))\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User user = new User();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(attributes != null &amp;amp;&amp;amp; attributes.getLength() == 1)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.setId(Integer.parseInt(attributes.getValue(0)));\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.objectStack.push(user);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;public void endElement(String uri, String localName, String qName) throws SAXException\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.elementStack.pop();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (\"user\".equals(qName))\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User object = this.objectStack.pop();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.userList.add(object);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;\/**\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;* This will be called everytime parser encounter a value node\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;* *\/\n&nbsp;&nbsp;&nbsp;&nbsp;public void characters(char&#91;] ch, int start, int length) throws SAXException\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String value = new String(ch, start, length).trim();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (value.length() == 0)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (\"firstName\".equals(currentElement()))\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User user = (User) this.objectStack.peek();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.setFirstName(value);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else if (\"lastName\".equals(currentElement()))\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User user = (User) this.objectStack.peek();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.setLastName(value);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;private String currentElement()\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return this.elementStack.peek();\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;public ArrayList getUsers()\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return userList;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. <strong>SAX Parser to read XML file:<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\n&nbsp;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.XMLReader;\nimport org.xml.sax.helpers.XMLReaderFactory;\n&nbsp;\npublic class UsersXmlParser\n{\n&nbsp;&nbsp;&nbsp;&nbsp;public ArrayList parseXml(InputStream in)\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ArrayList&lt;user&gt; users = new ArrayList&lt;\/user&gt;&lt;user&gt;();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UserParserHandler handler = new UserParserHandler();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;XMLReader parser = XMLReaderFactory.createXMLReader();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parser.setContentHandler(handler);\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;InputSource source = new InputSource(in);\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parser.parse(source);\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;users = handler.getUsers();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (SAXException e) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (IOException e) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} finally {\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return users;\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>5. Test SAX Parser:<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.util.ArrayList;\n&nbsp;\npublic class TestSaxParser\n{\n&nbsp;&nbsp;&nbsp;&nbsp;public static void main(String arg&#91;]) throws FileNotFoundException\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;File xmlFile = new File(\"D:\/temp\/sample.xml\");\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UsersXmlParser parser = new UsersXmlParser();\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ArrayList users = parser.parseXml(new FileInputStream(xmlFile));\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(users);\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Key Takeaways from SAX Parsing<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It processes Parse XML data sequentially.<\/li>\n\n\n\n<li>It is event-driven and memory-efficient.<\/li>\n\n\n\n<li>It does not allow backward traversal or modification of data.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">SAX vs. DOM: Which One Should You Choose?<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>SAX<\/th><th>DOM<\/th><\/tr><tr><td>Memory Usage<\/td><td>Low<\/td><td>High<\/td><\/tr><tr><td>Speed<\/td><td>Fast<\/td><td>Slower<\/td><\/tr><tr><td>Backward Traversal<\/td><td>Not Allowed<\/td><td>Allowed<\/td><\/tr><tr><td>Modification of Data<\/td><td>Not Possible<\/td><td>Possible<\/td><\/tr><tr><td>Best Use Case<\/td><td>Large XML files, Streaming Data<\/td><td>Small XML files, Data Manipulation<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Choosing between SAX and DOM depends on your application requirements. If you are working with large Parse XML files and need fast processing, SAX is the preferred choice. However, if you need to modify or access data randomly, DOM is a better option.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>XML parsing is an essential skill for any Java Full Stack Developer. Understanding SAX and DOM helps in making informed decisions when working with Parse XML data in Java applications. Whether you&#8217;re building a web service, processing configuration files, or handling structured data, mastering XML parsing will enhance your Java programming skills.<\/p>\n\n\n\n<p>Ready to elevate your Java expertise? Enroll in <a href=\"https:\/\/www.h2kinfosys.com\/\">H2K Infosys<\/a>\u2019 <strong>Java course<\/strong> today and gain hands-on experience in Java programming, Java Full Stack Development, and much more!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction In the world of Java programming, working with structured data is crucial, especially when dealing with XML files. How to Parse XML using SAX\/DOM? XML (Extensible Markup Language) is widely used in data storage, configuration files, and web services. Parsing XML efficiently is an essential skill for Java Full Stack Developers. When working with [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":4053,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[961,962,959,957,960,963,958],"class_list":["post-3677","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorials","tag-dom-interfaces","tag-dom-methods","tag-dom-parser","tag-parse-xml","tag-sax-parser","tag-simple-api-for-xml","tag-xml-parsing"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3677","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=3677"}],"version-history":[{"count":0,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3677\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/4053"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=3677"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=3677"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=3677"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}