Java SAX Parser – Create XML Document ”; Previous Next Java SAX Parser is a read-only parser which is used to read the XML documents in a forward read-only manner. We cannot create XML documents using a SAX parser. It is better to use StAX parser for creating XML documents rather than using SAX parser. Please refer the Java StAX Parser section for the same. Print Page Previous Next Advertisements ”;
Category: java Xml
Create XML Document
Java DOM4J Parser – Create XML Document ”; Previous Next Java DOM4J library has classes, interfaces and methods to create XML documents. The interfaces Document and Element of org.dom4j package has methods to create XML documents. The XMLWriter class of org.dom4j.io package writes the XML content of the document into the file. In this chapter we are going to use these interfaces and classes to create XML files. Create XML Using Java DOM4J Parser Following are the steps to create XML documents using Java DOM4J Parser − Step 1: Creating a new Document Step 2: Creating and Adding XML elements Step 3: Creating a FileOutputStream Step 4: Writing the XML document into file Step 5: Printing the XML document Step 1: Creating a new Document The DocumentHelper class of org.dom4j package provides the helper methods to use DOM4J. The createDocument() method creates a new document as follows − Document document = DocumentHelper.createDocument(); Step 2: Creating and Adding XML elements We can create root element and add it to the XML document using addElement() method. Also, we can add child elements to the root element using the same addElement() method. To add attributes, we use addAttribute() method. Element root = document.addElement( “root_ele_name” ); Element child = root.addElement(“child_ele_name”).addAttribute(“attr_name”, “attr_val”); Step 3: Creating a FileOutputStream To copy the content of XML document into a file, we need to create a FileOutputStream as follows − FileOutputStream newFile = new FileOutputStream(“D://newDOM4jFile.xml”); Step 4: Writing the XML document into file The XMLWriter class has write() method to write the XML document into the specified file. We can also send the format we want to add to the content as second argument to the write() method. XMLWriter writer = new XMLWriter(newFile); writer.write( document ); Step 5: Printing the XML document To print the content of XML document, we can pass System.out as the first argument and format as the second argument. The createPrettyPrint() method creates proper indentation of XML elements while displaying. This step is optional and can be used for testing purpose. OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter consoleWriter = new XMLWriter( System.out, format ); consoleWriter.write( document ); Creating XML file The addElement() method can be used with either Document or Element interface. This method takes name of the element as a parameter and adds it to the specified document or element. To add root element, we use Document.addElement(root_ele_name). The addAttribute() method takes name of the attribute as first argument and value as the second argument. It adds the attribute to the specified element. The addText() method adds the text content to the element. It takes the text content as a String and adds to the corresponding element. Example Using the methods discussed above, we are going to create an XML file with ”cars” as root element and company as its attribute. Let us add two ”carname” elements with ”type” as attribute. We need to create the following cars.xml file − <?xml version = “1.0” encoding = “UTF-8”?> <cars> <supercars company = “Ferrari”> <carname type = “formula one”>Ferrari 101</carname> <carname type = “sports”>Ferrari 202</carname> </supercars> </cars> The following CreateXMLDemo.java program creates a document and adds the elements using addElement() method and attributes using addAttribute() method. To set the text content, addText() method is used. The XML content of the document is transferred into a file and also printed on the console. package java_xml_dom4j; import java.io.FileOutputStream; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class CreateDemo { public static void main(String[] args) { try { //Creating a new Document Document document = DocumentHelper.createDocument(); //Creating and Adding XML elements Element root = document.addElement( “cars” ); Element supercarElement = root.addElement(“supercars”) .addAttribute(“company”, “Ferrai”); supercarElement.addElement(“carname”) .addAttribute(“type”, “Ferrari 101”) .addText(“Ferrari 101”); supercarElement.addElement(“carname”) .addAttribute(“type”, “sports”) .addText(“Ferrari 202”); //Creating a FileOutputStream FileOutputStream newFile = new FileOutputStream(“D://newDOM4jFile.xml”); //Writing the XML document into file XMLWriter writer = new XMLWriter(newFile); writer.write( document ); //Printing the XML document OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter consoleWriter = new XMLWriter( System.out, format ); consoleWriter.write( document ); } catch (Exception e) { e.printStackTrace(); } } } Output The output window displays the XML content as follows − <?xml version = “1.0” encoding = “UTF-8”?> <cars> <supercars company = “Ferrari”> <carname type = “formula one”>Ferrari 101</carname> <carname type = “sports”>Ferrari 202</carname> </supercars> </cars> Print Page Previous Next Advertisements ”;
Java XML – Quick Guide
Java XML – Quick Guide ”; Previous Next Java XML – Overview What is XML? XML is a simple text-based language which was designed to store and transport data in plain text format. It stands for Extensible Markup Language. Following are some of the salient features of XML. XML is a markup language. XML is a tag based language like HTML. XML tags are not predefined like HTML. You can define your own tags which is why it is called extensible language. XML tags are designed to be self-descriptive. XML is W3C Recommendation for data storage and data transfer. Example <?xml version = “1.0”?> <Class> <Name>First</Name> <Sections> <Section> <Name>A</Name> <Students> <Student>Rohan</Student> <Student>Mohan</Student> <Student>Sohan</Student> <Student>Lalit</Student> <Student>Vinay</Student> </Students> </Section> <Section> <Name>B</Name> <Students> <Student>Robert</Student> <Student>Julie</Student> <Student>Kalie</Student> <Student>Michael</Student> </Students> </Section> </Sections> </Class> Advantages Following are the advantages that XML provides − Technology agnostic − Being plain text, XML is technology independent. It can be used by any technology for data storage and data transfer purpose. Human readable − XML uses simple text format. It is human readable and understandable. Extensible − In XML, custom tags can be created and used very easily. Allow Validation − Using XSD, DTD and XML structures can be validated easily. Disadvantages Following are the disadvantages of using XML − Redundant Syntax − Normally XML files contain a lot of repetitive terms. Verbose − Being a verbose language, XML file size increases the transmission and storage costs. Java XML – Parsers XML Parsing refers to going through an XML document in order to access or modify data. What is XML Parser? XML Parser provides a way to access or modify data in an XML document. Java provides multiple options to parse XML documents. Following are the various types of parsers which are commonly used to parse XML documents. Dom Parser − Parses an XML document by loading the complete contents of the document and creating its complete hierarchical tree in memory. SAX Parser − Parses an XML document on event-based triggers. Does not load the complete document into the memory. JDOM Parser − Parses an XML document in a similar fashion to DOM parser but in an easier way. StAX Parser − Parses an XML document in a similar fashion to SAX parser but in a more efficient way. XPath Parser − Parses an XML document based on expression and is used extensively in conjunction with XSLT. DOM4J Parser − A java library to parse XML, XPath, and XSLT using Java Collections Framework. It provides support for DOM, SAX, and JAXP. There are JAXB and XSLT APIs available to handle XML parsing in object-oriented way. We”ll elaborate each parser in detail in the subsequent chapters of this tutorial. Java DOM Parser – Overview The Document Object Model (DOM) is an official recommendation of the World Wide Web Consortium (W3C). It defines an interface that enables programs to access and update the style, structure, and contents of XML documents. XML parsers that support DOM implement this interface. When to Use? You should use a DOM parser when − You need to know a lot about the structure of a document. You need to move parts of an XML document around (you might want to sort certain elements, for example). You need to use the information in an XML document more than once. What You Get? When you parse an XML document with a DOM parser, you get back a tree structure that contains all of the elements of your document. The DOM provides a variety of functions you can use to examine the contents and structure of the document. Advantages The DOM is a common interface for manipulating document structures. One of its design goals is that Java code written for one DOM-compliant parser should run on any other DOM-compliant parser without having to do any modifications. DOM interfaces The DOM defines several Java interfaces. Here are the most common interfaces − Node − The base datatype of the DOM. Element − The vast majority of the objects you”ll deal with are Elements. Attr − Represents an attribute of an element. Text − The actual content of an Element or Attr. Document − Represents the entire XML document. A Document object is often referred to as a DOM tree. Common DOM methods When you are working with DOM, there are several methods you”ll use often − Document.getDocumentElement() − Returns the root element of the document. Node.getFirstChild() − Returns the first child of a given Node. Node.getLastChild() − Returns the last child of a given Node. Node.getNextSibling() − These methods return the next sibling of a given Node. Node.getPreviousSibling() − These methods return the previous sibling of a given Node. Node.getAttribute(attrName) − For a given Node, it returns the attribute with the requested name. Java DOM Parser – Parse XML Document Steps to Using JDOM Following are the steps used while parsing a document using JDOM Parser. Import XML-related packages. Create a DocumentBuilder Create a Document from a file or stream Extract the root element Examine attributes Examine sub-elements Import XML-related packages import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; Create a DocumentBuilder DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Create a Document from a file or stream StringBuilder xmlStringBuilder = new StringBuilder(); xmlStringBuilder.append(“<?xml version=”1.0”?> “); ByteArrayInputStream input = new ByteArrayInputStream( xmlStringBuilder.toString().getBytes(“UTF-8”)); Document doc = builder.parse(input); Extract the root element Element root = document.getDocumentElement(); Examine attributes //returns specific attribute getAttribute(“attributeName”); //returns a Map (table) of names/values getAttributes(); Examine sub-elements //returns a list of subelements of specified name getElementsByTagName(“subelementName”); //returns a list of all child nodes getChildNodes(); Demo Example Here is the input xml file that we need to parse − <?xml version = “1.0”?> <class> <student rollno = “393”> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = “493”> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = “593”> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> DomParserDemo.java package com.tutorialspoint.xml; import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; public class DomParserDemo { public static void main(String[] args)
Java XPath Parser
Java XPath Parser – Overview ”; Previous Next XPath is an XML Path language to find information in an XML file. It is an official recommendation of the World Wide Web Consortium (W3C). It is used to traverse elements and attributes of an XML document. XPath provides various types of expressions which can be used to enquire relevant information from the XML document and it is mainly used in XSLT standard. XPath Terminology Structure Definitions − XPath defines the parts of an XML document like element, attribute, text, namespace, processing-instruction, comment, and document nodes. Path Expressions − XPath provides powerful path expressions such as select nodes or list of nodes in XML documents. Standard Functions − XPath provides a rich library of standard functions for manipulation of string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, etc. Axes − XPath has thirteen different axes that retrieves the relative elements of the current element such as ancestor, child, descendant, preceding, following etc. XPath Expressions XPath uses a path expression to select node or list of nodes from an XML document. Following is a list of useful path expressions to select any node/list of nodes from an XML document. Expression Description node-name Selects all nodes with the given “nodename” / Selection starts from the root node // Selection starts from the current node that match the selection . Selects the current node .. Selects the parent of the current node @ Selects attributes student Selects all nodes with the name “student” class/student Selects all student elements that are children of class //student Selects all student elements no matter where they are in the document Expressions with Predicates XPath expressions can be used along with predicates to obtain a specific node or a node containing specific value and are defined using […]. Expression Result /class/student[1] Selects the first student element that is the child of the class element. /class/student[last()] Selects the last student element that is the child of the class element. /class/student[last()-1] Selects the last but one student element that is the child of the class element. //student[@rollno = ”493”] Selects all the student elements that have an attribute named rollno with a value of ”493” Print Page Previous Next Advertisements ”;
Create XML Document
Java DOM Parser – Create XML Document ”; Previous Next Java DOM parser API has methods, interfaces and classes to create XML documents. Using this API, we can create XML documents from the scratch through our Java applications. The createElement() method creates new elements and the appendChild() method appends the created elements to already existing elements. Create XML Using Java DOM Parser We can create an XML document in Java using DOM parser through following steps − Step 1: Creating a DocumentBuilder Object Step 2: Create a new Document Step 3: Creating the root element Step 4: Appending elements to the root element Step 5: Writing the content into XML file Step 6: Testing the output using console Refer this page for step 1. Step2: Create a new Document Using DocumentBuilder object created in the above step, create a new document with newDocument() function. Document doc = dBuilder.newDocument(); Step3: Creating the root element Every XML document should possess a single root element , which is also called a parent element. We can create the root element using createElement() method and append it to the document created in the previous step. Element rootElement = doc.createElement(“root”); doc.appendChild(rootElement); Step 4: Appending elements to the root element Inside the root element, we can create any number of child elements and append them the same way we appended root element to the document. To write text content inside an element, we can use createTextNode() method. We can also create attributes for elements using createAttribute() method. Element child = doc.createElement(“child”); rootElement.appendChild(child); child.appendChild(doc.createTextNode(“text_content_here”)); Attr attr = doc.createAttribute(“child”); Step 5: Writing the content into XML file After building the elements inside the document with their corresponding attributes, we need to write this content into an XML file by creating Tranformer object, which in-turn transforms our source document into StreamResult and stores it in the specified file path with the given name. TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(“filepath:\new.xml”)); transformer.transform(source, result); Step 6: Testing the output using console We can test our XML file by printing it on the console. This is an optional step. StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); Creating Basic XML File To create a document element, we use the method createElement(“element_name”). This method takes element name as an argument and returns a new Element object. After getting the new Element object, we can use appendChild(Element) method to append this Element object to the document. This method is also used to append an element to another element (creating child elements). cars.xml We want to create the following xml file with the name “cars.xml” in D drive. <cars> <supercars>Ferrari</supercars> </cars> CreateXMLDemo.java In the following code, we have created one root element with name “cars” and appended one child element with name “supercars”. We have also added text content to supercars element. import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; 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; import org.w3c.dom.Element; import java.io.File; public class CreateXMLDemo { public static void main(String argv[]) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Create a new Document Document doc = dBuilder.newDocument(); //Creating the root element Element rootElement = doc.createElement(“cars”); doc.appendChild(rootElement); //Appending elements to the root element Element supercar = doc.createElement(“supercars”); rootElement.appendChild(supercar); supercar.appendChild(doc.createTextNode(“Ferrari”)); //writing the content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(“D:\cars.xml”)); transformer.transform(source, result); //Output to console for testing StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) {e.printStackTrace();} } } Output For testing, we have printed the document output on the console. <?xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?><cars><supercars>Ferrari</supercars></cars> Creating XML File with Attributes Attributes can be created to an Element using the method, createAttribute(“Attribute_name”). This method of Document interface takes name of the attribute as an argument and returns the Attr object. The setValue(“value”) method is used to set the value of the attribute. Now, to set this attribute node to the Element, we use setAttributeNode(Attr) method with the Element object to which we need to set this attribute. newcars.xml We need to create the following “newcars.xml” in D drive. <cars> <supercars company=”Ferrari”> <carname type=”formula one”>Ferrari 101</carname> <carname type=”sports”>Ferrari 202</carname> </supercars> </cars> CreateXMLAttributeDemo.java We have created two carname elements for supercars element. Also, using setAttributeNode() method, we have added two attributes for each of the carname elements. import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; 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.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; public class CreateXMLAttributeDemo { public static void main(String argv[]) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Creating a new Document Document doc = dBuilder.newDocument(); //Creating the root element Element rootElement = doc.createElement(“cars”); doc.appendChild(rootElement); //Appending sub element to the root element Element supercar = doc.createElement(“supercars”); rootElement.appendChild(supercar); //Setting attribute to the sub element Attr attr = doc.createAttribute(“company”); attr.setValue(“Ferrari”); supercar.setAttributeNode(attr); //Adding First child element to sub element Element carname = doc.createElement(“carname”); Attr attrType = doc.createAttribute(“type”); attrType.setValue(“formula one”); carname.setAttributeNode(attrType); carname.appendChild(doc.createTextNode(“Ferrari 101”)); supercar.appendChild(carname); //Adding second child element to sub element Element carname1 = doc.createElement(“carname”); Attr attrType1 = doc.createAttribute(“type”); attrType1.setValue(“sports”); carname1.setAttributeNode(attrType1); carname1.appendChild(doc.createTextNode(“Ferrari 202”)); supercar.appendChild(carname1); //writing the content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(“D:\newcars.xml”)); transformer.transform(source, result); //Output to console for testing StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } } } Output For testing, we have printed the document output
Modify XML Document
Java JDOM Parser – Modify XML Document ”; Previous Next Java JDOM parser is an API in java that has classes and interfaces to modify XML documents. This API represents the XML document in the form of a tree structure and each element can be retrieved easily. Hence, modification becomes an easy task. We can use setText() to modify content and addContent() to add new elements. In this chapter, we are going to see how to modify an existing XML document with two examples. Modify XML using JDOM Parser We can modify an XML document in java JDOM parser through following steps − Step 1: Creating a SAXBuilder Object Step 2: Reading the XML Step 3: Parsing the XML Document Step 4: Updating the content of XML document Step 5: Writing the content into XML file Step 6: Output to console for testing Refer second chapter of this section for first three steps. Step 4: Updating the content of XML document After following the first three steps, we have successfully read the XML document we need to update. Now, we have the XML file in the form of JDOM document. To get any information from the document, firstly, we should always get the root element. After retrieving the root element, we can get the information of all the elements inside the root. Refer this chapter of this section for steps 5 and 6. Updating Text Content To update text content of any element, we can use the setText() method of Element class. This method takes the text content as an argument in the form of a String. If text content already exists, it updates the old one with the new text content. Example Here, we have college.xml file that has three department elements. We are going to modify the staff count for department with id, 102 from 23 to 14. <?xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?><college> <department id=”101″> <name>Computer Science</name> <staffCount>20</staffCount> </department> <department id=”102″> <name>Electrical and Electronics</name> <staffCount>23</staffCount> </department> <department id=”103″> <name>Mechanical</name> <staffCount>15</staffCount> </department> </college> The following ModifyTextContent.java program reads the above college.xml file using SAXBuilder object. After getting the list of department elements, we are using getAttributeValue() method to find the department with id, 102. Later, we are updating the text content using setText() method. import java.io.File; import java.util.List; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.transform.JDOMSource; public class ModifyTextContent { public static void main(String args[]) { try { //Creating a SAXBuilder Object SAXBuilder saxBuilder = new SAXBuilder(); //Reading the XML File inputFile = new File(“college.xml”); //Parsing the XML Document Document doc = saxBuilder.build(inputFile); //Retrieving the Root Element Element RootElement = doc.getRootElement(); List<Element> deptList = RootElement.getChildren(“department”); //Finding “department” with id=102 in the list for(int index=0; index<deptList.size();index++) { Element department = deptList.get(index); if(department.getAttributeValue(“id”).equals(“102”)) { Element staffCount = department.getChild(“staffCount”); //Updating the staff count staffCount.setText(“14”); break; } } //writing the modified content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); JDOMSource source = new JDOMSource(doc); StreamResult result = new StreamResult(new File(“college.xml”)); transformer.transform(source, result); //Output to console for testing XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, System.out); } catch(Exception e) { e.printStackTrace(); } } } Output Following is the updated XML document after updating staffCount. <?xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?><college> <department id=”101″> <name>Computer Science</name> <staffCount>20</staffCount> </department> <department id=”102″> <name>Electrical and Electronics</name> <staffCount>14</staffCount> </department> <department id=”103″> <name>Mechanical</name> <staffCount>15</staffCount> </department> </college> Adding New Elements The addContent() method of Element class takes child element and append it one level deep to the current element. It always adds the new Element at the end. If we pass two arguments, index and child element, then the child element gets inserted at the specified index. Example Now, we are going to add one more department named “Civil” to our college element in the following AddNewElements.java program. We have created the child elements of the department and added them to the department element. Later we added the department to the root element. import java.io.File; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.transform.JDOMSource; public class AddNewElements { public static void main(String args[]) { try { //Creating a SAXBuilder Object SAXBuilder saxBuilder = new SAXBuilder(); //Reading the XML File inputFile = new File(“college.xml”); //Parsing the XML Document Document doc = saxBuilder.build(inputFile); //Retrieving the Root Element Element RootElement = doc.getRootElement(); //Creating new “department” Element Element department=new Element(“department”); department.setAttribute(“id”,”104″); //Creating “name” Element for department Element name=new Element(“name”); name.setText(“Civil”); //Creating “staffCount” Element for department Element staffCount=new Element(“staffCount”); staffCount.setText(“18”); //Appending Elements department.addContent(name); department.addContent(staffCount); RootElement.addContent(department); //writing the modified content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); JDOMSource source = new JDOMSource(doc); StreamResult result = new StreamResult(new File(“college.xml”)); transformer.transform(source, result); //Output to console for testing XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, System.out); } catch(Exception e) { e.printStackTrace(); } } } Output The updated file after adding “Civil” department is as follows : <?xml version=”1.0″ encoding=”UTF-8″?> <college> <department id=”101″> <name>Computer Science</name> <staffCount>20</staffCount> </department> <department id=”102″> <name>Electrical and Electronics</name> <staffCount>23</staffCount> </department> <department id=”103″> <name>Mechanical</name> <staffCount>15</staffCount> </department> <department id=”104″> <name>Civil</name> <staffCount>18</staffCount> </department> </college> Print Page Previous Next Advertisements ”;
Modify XML Document
Java StAX Parser – Modify XML Document ”; Previous Next Java StAX Parser is a java API which provides interfaces, classes and methods to parse and modify XML documents. Random access of XML elements is not possible using StAX parser and hence, we need to store the required data as the parser parses the XML document. We can use XMLEventReader to read the XML document and XMLEventWriter to write the updated content simultaneously. Modify XML Using Java StAX Parser We can modify an XML document in Java using StAX parser through following steps − Step 1: Creating XMLInputFactory instance Step 2: Reading the XML Step 3: Parsing the XML Step 4: Modifying the XML content Step 5: Creating XMLStreamReader object Step 6: writing the updated content into XML file Refer Parse XML Document of this section for first three steps Step 4: Modifying the XML content After following the first three steps, we have our XML file in XMLEventReader object. Since, we don”t have random access of XML elements, we can read and write the XML content simultaneously. Here, updating means simply creating new events and adding them in the place of old events. To create any XMLEvent, we should first get the instance of XMLEventFactory. Using XMLEventFactory, we can add new elements and attributes. XMLEventFactory eventFactory=XMLEventFactory.newInstance(); Refer Create XML Document chapter of this section for steps 5 and 6. Updating Text Content The createCharacters(“text”) method of XMLEventFactory creates character content with the text specified and returns Characters event. This event can be added to the XMLEventWriter using add() function. Example Here is the studentData.xml file in which we need to update the marks for the student with roll number 593. <?xml version = “1.0”?> <class> <student rollno = “393”> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = “493”> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = “593”> <firstname>jasvir</firstname> <lastname>singh</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> In the following UpdatingTextContent.java program, we have used two boolean variables studentFound and marksFound to identify that student with the roll number 593. We are adding all the events to XMLEventWriter except the Characters event of marks for student with roll number 593. We are creating a new Characters event for that student and adding it to the XMLEventWriter. import java.io.FileReader; import java.io.StringWriter; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class UpdatingTextContent { public static void main(String[] args) { try { //Creating XMLInputFactory instance XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading the XML FileReader fileReader = new FileReader(“studentData.xml”); //Parsing the XML XMLEventReader eventReader = factory.createXMLEventReader(fileReader); //Updating text content StringWriter stringWriter = new StringWriter(); XMLOutputFactory outFactory = XMLOutputFactory.newInstance(); XMLEventWriter eventWriter = outFactory.createXMLEventWriter(stringWriter); XMLEventFactory eventFactory=XMLEventFactory.newInstance(); boolean studentFound=false; boolean marksFound=false; while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if(event.getEventType()==XMLStreamConstants.START_ELEMENT) { StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); Attribute attr = startElement.getAttributeByName(new QName(“rollno”)); if (qName.equalsIgnoreCase(“student”) && attr.getValue().equals(“593”)) { studentFound=true; } if (qName.equalsIgnoreCase(“marks”) && studentFound) { studentFound = false; marksFound=true; } } if(event.getEventType()==XMLStreamConstants.CHARACTERS && marksFound) { eventWriter.add(eventFactory.createCharacters(“64”)); marksFound=false; } else { eventWriter.add(event); } } String xmlString = stringWriter.getBuffer().toString(); System.out.println(xmlString); } catch (Exception e) { e.printStackTrace(); } } } The output window displays the student data with the marks modified for student with roll number 593. <?xml version = “1.0”?> <class> <student rollno = “393”> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = “493”> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = “593”> <firstname>jasvir</firstname> <lastname>singh</lastname> <nickname>jazz</nickname> <marks>64</marks> </student> </class> Adding Elements to Existing XML File The add(XMLEvent event) function of XMLEventWriter adds the event to the Writer or the OutputStream specified while creating XMLEventWriter. Adding a new StartElement event opens the new namespace scope and will be closed when an EndElement event is added. Using the same studentData.xml file that we have discussed in the previous example, we are going to add new student element with all the necessary information. Example In the following AddXMLElements.java program, we have added all the events to the XMLEventWriter till the last student element. We have added the new student element at the end and then closed the root element. To find the exact position of adding the new element, we used peek() method, since it just shows the peek event instead of reading it from the stream. import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileReader; import java.io.StringWriter; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; public class AddXMLElements { public static void main(String[] args) { try { //Creating XMLInputFactory instance XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading the XML FileReader fileReader = new FileReader(“studentData.xml”); //Parsing the XML XMLEventReader eventReader = factory.createXMLEventReader(fileReader); //Modifying the XML content StringWriter stringWriter = new StringWriter(); XMLOutputFactory outFactory = XMLOutputFactory.newInstance(); XMLEventWriter eventWriter = outFactory.createXMLEventWriter(stringWriter); XMLEventFactory eventFactory=XMLEventFactory.newInstance(); while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if(event.getEventType()==XMLStreamConstants.END_ELEMENT && eventReader.peek().getEventType()==XMLStreamConstants.END_DOCUMENT ) { eventWriter.add(eventFactory.createStartElement(“”, “”, “student”)); eventWriter.add(eventFactory.createAttribute(“rollno”, “693”)); eventWriter.add(eventFactory.createStartElement(“”, “”, “firstname”)); eventWriter.add(eventFactory.createCharacters(“Daniel”)); eventWriter.add(eventFactory.createEndElement(“”, “”, “firstname”)); eventWriter.add(eventFactory.createStartElement(“”, “”, “lastname”)); eventWriter.add(eventFactory.createCharacters(“Wesley”)); eventWriter.add(eventFactory.createEndElement(“”, “”, “lastname”)); eventWriter.add(eventFactory.createStartElement(“”, “”, “nickname”)); eventWriter.add(eventFactory.createCharacters(“Dany”)); eventWriter.add(eventFactory.createEndElement(“”, “”, “nickname”)); eventWriter.add(eventFactory.createStartElement(“”, “”, “marks”)); eventWriter.add(eventFactory.createCharacters(“75”)); eventWriter.add(eventFactory.createEndElement(“”, “”, “marks”)); eventWriter.add(eventFactory.createEndElement(“”, “”, “student”)); } else { eventWriter.add(event); } } //Creating XMLStreamReader object String xmlString = stringWriter.getBuffer().toString(); ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes(“UTF-8”)); stringWriter.close(); XMLStreamReader streamReader = factory.createXMLStreamReader(input); //writing the updated content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StAXSource source = new StAXSource(streamReader); StreamResult result = new StreamResult(new File(“studentData.xml”)); transformer.transform(source, result); System.out.println(xmlString); } catch (Exception e) { e.printStackTrace(); } } } Output This is the content of the output file after adding new student information− <?xml version = “1.0”?> <class> <student rollno = “393”> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = “493”> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = “593”> <firstname>jasvir</firstname> <lastname>singh</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> <student rollno=”693″> <firstname>Daniel</firstname> <lastname>Wesley</lastname> <nickname>Dany</nickname> <marks>75</marks> </student> </class> Print Page Previous Next Advertisements ”;
Query XML Document
Java StAX Parser – Query XML Document ”; Previous Next Java StAX parser is a Java API which is used to parse XML documents and query the necessary information. This API is event based and hence we need not load entire XML document to query it. As the parser identifies each event, the corresponding action is performed only when the client program implements the event. In this chapter, we are going to see how to query an XML document to get necessary information. Query XML Using Java StAX Parser Following are the steps we need to follow to query an XML document using Java StAX parser − Step 1: Creating XMLInputFactory instance Step 2: Reading the XML Step 3: Parsing the XML Step 4: Querying the Elements Refer this chapter for first three steps Step 4: Querying the Elements After following the first three steps, we have XMLEventReader to get events from the XML document. Using various events and by implementing them, we can query the XML document. Let us see how we can do this in detail. Querying Elements by Text Content We can get the text content in any element of an XML document by using getData().This method of Characters interface returns the character data of the current event in the form of a String. Using this method, we can query all the elements to find the required text content. Example The cars.xml file shown below has many carname elements with different text content. Let us query this file to find out if “Bentley 2” car is present. <?xml version = “1.0”?> <cars> <carname company=”Ferarri” >Ferarri 101</carname> <carname company=”Lamborgini”>Lamborgini 001</carname> <carname company=”Lamborgini”>Lamborgini 002</carname> <carname company=”Lamborgini”>Lamborgini 003</carname> <carname company=”Bentley”>Bentley 1</carname> <carname company=”Bentley”>Bentley 2</carname> <carname company=”Bentley”>Bentley 3</carname> </cars> The following QueryTextContent.java program reads the cars.xml file using a FileReader object. When the CHARACTERS event type is encountered, the getData() method is used to get the text content. If that data is equal to “Bentley 2″, then we are updating the ”found” boolean variable. In the END_DOCUMENT event, we are printing it on the console. import java.io.FileReader; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.events.Characters; import javax.xml.stream.events.XMLEvent; public class QueryTextContent { public static void main(String args[]) { try { //Creating XMLInputFactory instance XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading the XML FileReader fileReader = new FileReader(“cars.xml”); //Parsing the XML XMLEventReader eventReader = factory.createXMLEventReader(fileReader); //Querying the XML boolean found=false; while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if(event.getEventType()==XMLStreamConstants.CHARACTERS) { Characters characters = event.asCharacters(); String textContent = characters.getData(); if(textContent.equals(“Bentley 2”)) found=true; } if(event.getEventType()==XMLStreamConstants.END_DOCUMENT) { if(found) System.out.println(“Bentley 2 car is found”); else System.out.println(“Bentley 2 car is not found”); } } } catch(Exception e) { e.printStackTrace(); } } } Output Since, Bentley 2 car is present in cars.xml file, it prints that it is found. Bentley 2 car is found Querying Elements by Attributes The getAttributeByName() method of an Element interface takes the QName object which is the qualified XML name of an attribute and returns the Attribute object. Further, the getValue() method of Attribute interface is used to get the value of the attribute in the form of a String. Example 1 The cars.xml file that we have used in the previous example is parsed in the following QueryAttributes.java program to count the number of Bentley cars present in the XML file. A count variable is incremented each time the company attribute of the carname element is equal to Bentley. import java.io.FileReader; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class QueryExample2 { public static void main(String args[]) { try { //Creating XMLInputFactory instance XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading the XML FileReader fileReader = new FileReader(“cars.xml”); //Parsing the XML XMLEventReader eventReader = factory.createXMLEventReader(fileReader); //Querying the XML document int count=0; while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if(event.getEventType()==XMLStreamConstants.START_ELEMENT) { StartElement element=event.asStartElement(); QName qname=new QName(“company”); Attribute attr=element.getAttributeByName(qname); if(attr!=null && attr.getValue().equals(“Bentley”)) count++; } } System.out.println(“No.of Bentley cars found : ” + count); } catch(Exception e) { e.printStackTrace(); } } } The number of Bentley cars in the XML file are displayed. No.of Bentley cars found : 3 Example 2 In this example, we are going to retrieve the information of a particular student based on their roll number. Here is the student.xml file we need to query − <?xml version = “1.0”?> <class> <student rollno = “393”> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = “493”> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = “593”> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> In the following QueryStudent.java program, we have checked for the events START_ELEMENT, CHARACTERS and END_ELEMENT and performed actions accordingly. when the roll number attribute is equal to 393, we are printing the entire information of the student. import java.io.FileReader; import java.util.Iterator; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class QueryStudent { public static void main(String[] args) { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; boolean isRequestRollNo = false; try { //Creating XMLInputFactory instance XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading the XML FileReader fileReader = new FileReader(“student.xml”); //Parsing the XML XMLEventReader eventReader = factory.createXMLEventReader(fileReader); //Querying the XML String requestedRollNo = “393”; while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch(event.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); if (qName.equalsIgnoreCase(“student”)) { Iterator<Attribute> attributes = startElement.getAttributes(); String rollNo = attributes.next().getValue(); if(rollNo.equalsIgnoreCase(requestedRollNo)) { System.out.println(“Start Element : student”); System.out.println(“Roll No : ” + rollNo); isRequestRollNo = true; } } else if (qName.equalsIgnoreCase(“firstname”)) { bFirstName = true; } else if (qName.equalsIgnoreCase(“lastname”)) { bLastName = true; } else if (qName.equalsIgnoreCase(“nickname”)) { bNickName = true; } else if (qName.equalsIgnoreCase(“marks”)) { bMarks = true; } break; case XMLStreamConstants.CHARACTERS: Characters characters = event.asCharacters(); if(bFirstName && isRequestRollNo) { System.out.println(“First Name: ” + characters.getData()); bFirstName = false; } if(bLastName && isRequestRollNo) { System.out.println(“Last Name: ” + characters.getData()); bLastName = false; } if(bNickName && isRequestRollNo) { System.out.println(“Nick Name: ” + characters.getData()); bNickName = false; } if(bMarks && isRequestRollNo) { System.out.println(“Marks: ” + characters.getData()); bMarks = false; } break; case XMLStreamConstants.END_ELEMENT: EndElement endElement =
Java StAX Parser
Java StAX Parser – Overview ”; Previous Next StAX is a Java-based API to parse XML document in a similar way as SAX parser does. But unlike SAX parser, the StAX parser API is a simple iterator based API that gives parsing control to the client program. It reads the XML document in a forward-only fashion and stores the events in an iterator. The client can ask for the events that he wants to access based on the event type of each event. Differences Between SAX and StAX Parsers Here are some notable differences between SAX and StAX parsers − SAX Parser StAX Parser Push based stream parser Pull based stream parser XML documents cannot be created XML documents cannot be created Gives less parsing control to client program Gives more parsing control to client program Not Iterator based API Iterator based API Handler class must be implemented No need to implement any Handler class Provides schema validation Doesn”t provide schema validation Environment Setup In order to use StAX parser, you should have stax.jar in your application”s classpath. Features of StAX Following are the features of StAX API − Reads the XML document from top to bottom and identifies the tokens. Processes the tokens in the same order of their appearance. Reports the parser about the nature of the tokens. Invokes the callback methods in the Event handler based on the identified tokens. When to Use Java StAX Parser? You should use a StAX parser when − You want to process an XML document in a linear fashion from top to bottom. The document is not deeply nested. Your XML document is very large. The problem to be solved involves only a part of the XML document. You have streaming data (data is available as soon as it is seen by the parser). Disadvantages of StAX Following are the disadvantages of StAX parser − We have no random access to an XML document, since it is processed in a forward-only manner. XML schema validation is not supported. If you need to keep track of data that the parser has seen or where the parser has changed the order of items, then you must write the code and store the data on your own. XMLEvent Interface This interface provides the basic Event representation of all components of an XML document. The event type differentiates each event and the information is retrieved accordingly. Some of the most commonly used methods of this interface are as follows − Method Description StartElement asStartElement() Retrieves StartElement object from this event. EndElement asEndElement() Retrieves EndElement object from this event. Characters asCharacters() Retrieves characters such as CDATA, whitespace, etc. from this event int getEventType() Returns the integer code for this event. XMLEventReader Interface This interface provides iterator of events which can be used to iterate over events as they occur while parsing an XML document. Some of the most commonly used methods are listed below − Method Description boolean hasNext() Returns true if there are more events in the EventReader, else retruns false. XMLEvent nextEvent() Returns the next XMLEvent in the EventReader. XMLEvent peek() Returns the next XMLEvent without reading it from the stream. XMLEventWriter Interface This interface writes XML documents by adding events. Some of the most commonly used methods are listed below − Method Description void add(Event event) Adds the event containing elements to XML. void flush() Writes any cached events to the stream. void close() Closes all resources related to the stream. XMLStreamReader Interface This interface provides efficient way of reading XML events in a forward, read-only manner. Some of its methods are listed below − Method Description int next() Used to retrieve next event. boolean hasNext() Used to check further events exists or not. String getText() Used to get text of the current parsing event. String getLocalName() Used to get local name of the current event. XMLStreamWriter Interface This Interface provides methods to write XML documents. Some of the most commonly used methods are listed below − Method Description void writeStartDocument() Adds XML declaration statement to the output stream. void writeStartElement(String localName) Adds a start element with given name. void writeEndElement(String localName) Adds an end element with given name. void writeAttribute(String localName, String value) Writes attribute with the specified name and value to an element. Print Page Previous Next Advertisements ”;
Parse XML Document
Java DOM Parser – Parse XML Document ”; Previous Next Java DOM parser is a Java API to parse any XML document. Using the methods provided, we can retrieve root element, sub elements and their attributes using Java DOM parser. In this tutorial we have used the getTagName() method to retrieve the tag name of elements, getFirstChild() to retrieve the first child of an element and getTextContent() to get the text content of elements. Parse XML Using Java DOM parser Having discussed various XML parsers available in Java, now let us see how we can use DOM parser to parse an XML file. We use parse() method to parse an XML file. Before jumping into the example directly, let us see the steps to parse XML document using Java DOM parser − Step 1: Creating a DocumentBuilder Object Step 2: Reading the XML Step 3: Parsing the XML Document Step 4: Retrieving the Elements Step 1: Creating a DocumentBuilder Object DocumentBuilderFactory is a factory API to obtain parser to parse XML documents by creating DOM trees. It has ”newDocumentBuilder()” method that creates an instance of the class ”DocumentBuilder”. This DocumentBuilder class is used to get input in the form of streams, files, URLs and SAX InputSources. DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Step 2: Reading the XML Input can be of file type or stream type. To input an XML file, Create a file object and pass the file path as argument. File xmlFile = new File(“input.xml”); To get input in the form of stream, we have used StringBuilder class and appended the input string and later converted it into bytes. The obtained ByteArrayInputStream is given as input to the document. StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<?xml version=”1.0″?> <rootElement></rootElement>”); ByteArrayInputStream input = new ByteArrayInputStream( xmlBuilder.toString().getBytes(“UTF-8″)); Step 3: Parsing the XML Document DocumentBuilder created in above steps is used to parse the input XML file. It contains a method named parse() which accepts a file or input stream as a parameter and returns a DOM Document object. If the given file or input stream is NULL, this method throws an IllegalArgumentException. Document xmldoc = docBuilder.parse(input); Step4: Retrieving the Elements The Node and Element interfaces of the org.w3c.dom. package provides various methods to retrieve desired information about elements from the XML documents. This information includes element”s name, text content, attributes and their values. We have many DOM interfaces and methods to get this information. Retrieving Root Element Name XML document constitutes of many elements. In Java an XML/HTML document is represented by the interface named Element. This interface provides various methods to retrieve, add and modify the contents of an XML/HTML document. We can retrieve the name of the root element using the method named getTagName() of the Element interface. It returns the name of the root element in the form of a string. Since Element is an interface, to create its object we need to use the getDocumentElement() method. This method retrieves and returns the root element in the form of an object. Example In the following example we have passed a simple XML document with just one root element ”college” using StringBuilder class. Then, we are retrieving it and printing on the console. import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; public class RetrieveRootElementName { public static void main(String[] args) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<college></college>”); //Parsing the XML Document ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); Document xmldoc = docBuilder.parse(input); //Retrieving the Root Element Name Element element = xmldoc.getDocumentElement(); System.out.println(“Root element name is “+element.getTagName()); } catch (Exception e) { e.printStackTrace(); } } } Output The element name, ”college” is displayed on the output screen as shown below − Root element name is college Parsing Single Sub Element in XML We can parse a simple XML document with single element inside the root element. So far, we have seen how to retrieve the root element. Now, let us see how to get the sub element inside the root element. Since, we have only one sub element, we are using getFirstChild() method to retrieve it. This method is used with the root element to get its first child. It returns the child node in the form of a Node object. After retrieving the child node, getNodeName() method is used to get the name of the node. It returns the node name in the form of a string. To get the text content, we use getTextContent() method. It returns the text content in the form of a String. Example Let us see the following example where we have one root element and a sub element. Here, ”college” is the root element with ”department” as sub element. The ”department” element has text content, “Computer Science”. We are retrieving the name and text content of the sub element. import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; public class SingleSubElement { public static void main(String[] args) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<college><department>Computer Science</department></college>”); //Parsing the XML Document ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); Document xmldoc = docBuilder.parse(input); //Retrieving the Root Element Element element = xmldoc.getDocumentElement(); //Retrieving the Child Node Node childNode = element.getFirstChild(); String childNodeName = childNode.getNodeName(); System.out.println(“Sub Element name : ” + childNodeName); //Retrieving Text Content of the Child Node “+ childNodeName); System.out.println(“Text content of Sub Element : “+childNode.getTextContent()); } catch (Exception e) { e.printStackTrace(); } } }