Java XPath Parser – Create XML Document ”; Previous Next XPath parser is used to navigate XML Documents only. It is better to use DOM parser for creating XML. Please refer the Java DOM Parser section for the same. Print Page Previous Next Advertisements ”;
Category: java Xml
Modify XML Document
Java XPath Parser – Modify XML Document ”; Previous Next XPath parser is used to navigate XML Documents only. It is better to use DOM parser for modifying XML. Please refer the Java DOM Parser section for the same. Print Page Previous Next Advertisements ”;
Query XML Document
Java JDOM Parser – Query XML Document ”; Previous Next Java JDOM parser is an API which has classes and methods to build JDOM documents from XML files to query related information. In this chapter, we are going to query elements by text content using getText() method and to query elements by attributes, we are using getAttributeValue() method. Query XML Using JDOM Parser Following are the steps we need to follow to query an XML document using JDOM parser − Step 1: Creating a SAXBuilder Object Step 2: Reading the XML Step 3: Parsing the XML Document Step 4: Querying the Elements Refer this chapter for first three steps Step 4: Querying the Elements After completing the first three steps, we get a JDOM document. Using classes and methods present in org.jdom2 package, we can start querying the elements and their attributes. Now, we are going to see two examples on how to query elements based on their text content and their attributes. We use the same cars.xml file for both the examples. Querying Elements by TextContent We can query elements by their text content, by first getting the root element using getRootElement() method. After we obtain the root element, we can use getChildren() function to get all the child elements. Then, we can query the elements by text content using getText() method. Example Consider the following cars.xml file with carname elements having company attribute and text content. Now, we are going to query this XML file to find “Bentley 2” car. <?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> In the following QueryXMLElements.java program, we are parsing the cars.xml file using SAXBuilder to query all the carname elements. After getting the carname elements in an Element list, we are iterating the list to find “Bentley 2” car. import java.io.File; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import java.util.List; public class QueryXMLElements { public static void main(String args[]) { try { //Creating a SAXBuilder Object SAXBuilder saxBuilder = new SAXBuilder(); //Reading the XML File inputFile = new File(“cars.xml”); //Parsing the XML Document Document document = saxBuilder.build(inputFile); //Retrieving the Root Element Element RootElement = document.getRootElement(); List<Element> carList = RootElement.getChildren(“carname”); //Finding “Bentley 2” car in the list boolean found=false; for(int index=0; index<carList.size();index++) { Element car = carList.get(index); if(car.getText().equals(“Bentley 2”)) { found=true; break; } } 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(); } } } The output window displays that the “Bentley 2” car is found in the XML file. Bentley 2 car is found Querying Elements by Attributes Elements can also have attributes along with the text content. Now, let use the same cars.xml file to query the carname elements by their company attribute. The getAttributeValue(“attr_name”) method of Element class takes attribute name as a String argument and returns the corresponding value of the attribute. Example In the following QueryAttributes.java program, we are getting the list of carname Elements from getChildren() method. Then, we are iterating the list and incrementing the count when the company attribute value is equal to “Bentley”. import java.io.File; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import java.util.List; public class QueryAttributes { public static void main(String args[]) { try { //Creating a SAXBuilder Object SAXBuilder saxBuilder = new SAXBuilder(); //Reading the XML File inputFile = new File(“cars.xml”); //Parsing the XML Document Document document = saxBuilder.build(inputFile); //Retrieving the Root Element Element RootElement = document.getRootElement(); List<Element> carList = RootElement.getChildren(“carname”); //Counting Bentley cars int count=0; for(int index=0; index<carList.size();index++) { Element car = carList.get(index); if(car.getAttributeValue(“company”).equals(“Bentley”)) { count++; } } System.out.println(“Total number of Bentley cars : ” + count); } catch(Exception e) { e.printStackTrace(); } } } Output The count value has the number of Bentley cars in the XML file and is printed on the console. Total number of Bentley cars : 3 Print Page Previous Next Advertisements ”;
Create XML Document
Java JDOM Parser – Create XML Document ”; Previous Next Java JDOM Parser is a Java API that has classes and methods to create XML documents from scratch. We can create a new JDOM document object and add elements, attributes using the methods available in Document and Element interfaces. In this chapter, we are going to use setRootElement(), addContent(), setText() and setAttribute() methods to create XML files in detail. Create XML using Java JDOM parser We can create an XML document in Java using JDOM parser through following steps − Step 1: Creating JDOM Document object Step 2: Creating and appending Root Element Step 3: Creating elements and attributes Step 4: Appending Elements to Root Step 5: Writing the content into XML file Step 6: Testing the output using console Step 1: Creating JDOM Document object The org.jdom2 package has Document class. It represents the XML document. This class has methods to access the root element and also the document level information. We create a new document as follows − Document doc = new Document(); Step 2: Creating and appending Root Element An XML document must contain a root element. We create root element using Element class of org.jdom2 package. If we provide a String to the constructor, it creates element with that supplied local name. The setRootElement() method in the Document class sets the root of the document. This method takes Element as an argument and sets it as the root. If the root element is already present, the old root Element gets replaced with this supplied Element. Element RootElement = new Element(“root”); doc.setRootElement(RootElement); Step 3: Creating elements and attributes We can create Elements the same way we created root element in the previous step. To set an attribute to the Element, we use setAttribute() method as follows − Element newElement = new Element(“FirstElement”); newElement.setAttribute(“attr_name”,”attr_value”); Step 4: Appending Elements to Root The Elements created in the previous step are now attached to the root element using addContent() method. This method takes single element or collection of elements in the form of content list and adds them to the element accordingly. RootElement.addContent(newElement); Step 5: Writing the content into XML file The TransformerFactory class is used to create a new instance of Transformer object. Using the transform() function in Transformer class, source is transformed to the destination result. We are creating JDOMSource object by passing document as a parameter. This JDOMSource object is transformed into StreamResult as follows − TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); JDOMSource source = new JDOMSource(doc); StreamResult result = new StreamResult(new File(“newFile.xml”)); transformer.transform(source, result); Step 6: Testing the output using console This is an optional step used for testing purpose. To print the output on the console, an XMLOutputter object is created and the Document object is passed as follows − XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, System.out); Creating Simple XML File Using, the above mentioned steps, let us create a simple XML file that has root element alone. A new document object is created and the Root element is attached using setRootElement() method. The setText() method of Element object takes the text content in the form of a String and attaches it to the Element. Example Here is the XML file we need to create. It has a root element named “cars” and the text content, “Ferrari”. <cars>Ferrari</cars> The following CreateXMLFile.java creates the XML file and stores it in D drive with the file name as “cars.xml”. 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.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.transform.JDOMSource; public class CreateXMLFile { public static void main(String[] args) { try{ //Creating JDOM Document object Document doc = new Document(); //Creating and appending Root Element Element carsElement = new Element(“cars”); carsElement.setText(“Ferrari”); doc.setRootElement(carsElement); //writing the content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); JDOMSource source = new JDOMSource(doc); StreamResult result = new StreamResult(new File(“D:\cars.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(); } } } For testing purpose, we have printed the content of XML document on the console. <?xml version=”1.0″ encoding=”UTF-8″?> <cars>Ferrari</cars> Creating Attributes Let us now add child elements to the root Element. Also, let us add attributes to our elements. In this example, we see how to create elements along with their attributes and attach them to the root. The setAttribute() method on each element sets the attribute and setText() method is used to set the text content of each element. Example Here is the cars.xml file that we need to create − <cars> <supercars company=”Ferrari”> <carname type=”formula one”>Ferrari 101</carname> <carname type=”sports”>Ferrari 202</carname> </supercars> </cars> The following CreateAttributes.java program creates the cars.xml file in D drive. import java.io.File; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.transform.JDOMSource; public class CreateAttributes { public static void main(String[] args) { try{ //Creating JDOM Document object Document doc = new Document(); //Creating and appending Root Element Element carsElement = new Element(“cars”); doc.setRootElement(carsElement); //Creating elements and attributes Element supercarElement = new Element(“supercars”); supercarElement.setAttribute(“company”,”Ferrari”); Element carElement1 = new Element(“carname”); carElement1.setAttribute(“type”,”formula one”); carElement1.setText(“Ferrari 101”); Element carElement2 = new Element(“carname”); carElement2.setAttribute(“type”,”sports”); carElement2.setText(“Ferrari 202”); supercarElement.addContent(carElement1); supercarElement.addContent(carElement2); //Appending Elements to Root carsElement.addContent(supercarElement); //writing the content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); JDOMSource source = new JDOMSource(doc); StreamResult result = new StreamResult(new File(“D:\Jdomcars.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(); } } } The output window displays the file 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 ”;
Query XML Document
Java DOM4J Parser – Query XML Document ”; Previous Next Java DOM4J parser is an open source Java library to parse and query the necessary information from XML documents. We can query XML documents using the methods of Document and Element interfaces of DOM4J. The elements() method retrieves all the elements of root element. Using attributeValue() method, we can query the attributes of elements. Query XML Using Java DOM4J Parser Following are the steps used while querying a document using Java DOM4J Parser − Step 1: Creating SAXReader object Step 2: Reading the XML file Step 3: Parsing the XML Step 4: Extracting the root Step 5: Querying the Document Refer Parse XML Document chapter of this section for first four steps. Step 5: Querying the Document After extracting the root in step 4, we can query the child elements using the root element. Now we are going to query XML documents by querying their elements and by querying their attributes. Querying Elements To get elements with specific name, we can use elements() method of Element interface and pass the name of the element we need to obtain as a parameter in the form of a string. This method returns the list of elements with the same name. The getData() method of Element interface returns the text data in the form of a String. To query an element based on its text content, we can use this method with equals() method for comparison. Example Following is the cars.xml file we need to query − <?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> Using the QueryElements.java program, we are querying the cars.xml file to find if there is “Bentley 2″ car available. We get all the ”carname” elements from elements() method and comparing the text content using getData() method. import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class QueryElements { public static void main(String[] args) { try { //Creating SAXReader SAXReader reader = new SAXReader(); //Reading the XML file File inputFile = new File(“cars.xml”); //Parsing the XML Document document = reader.read(inputFile); //Extracting the root Element RootElement = document.getRootElement(); List<Element> elements = RootElement.elements(“carname”); boolean found = false; //Iterating over the List for (Element ele : elements) { if(ele.getData().equals(“Bentley 2”)) { found = true; } } 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 The output window displays that ”Bentley 2” car is found in the document. Bentley 2 car is found Querying Attributes We can query for a specific attribute of an Element interface by using the attributeValue() method. We can pass a string value which is the name of the attribute as an argument to this method and it returns the value as a string. Example 1 The following QueryAttributes.java program gets the list of ”carname” elements and checks if the value of its attribute ”company” equals to ”Bentley” and the integer variable ”count” is incremented. import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class QueryAttributes { public static void main(String[] args) { try { //Creating SAXReader SAXReader reader = new SAXReader(); //Reading the XML file File inputFile = new File(“cars.xml”); //Parsing the XML Document document = reader.read(inputFile); //Extracting the root Element RootElement = document.getRootElement(); List<Element> elements = RootElement.elements(“carname”); int count = 0; for (Element ele : elements) { if(ele.attributeValue(“company”).equals(“Bentley”)) count++; } System.out.println(“No of Bentley cars found: ” + count); } catch (DocumentException e) { e.printStackTrace(); } } } Output The output window displays the number of Bentley cars found in the document. No of Bentley cars found: 3 Example 2 Consider the following studentData.xml file with three student elements inside the root element ”class”. Let us now try to print the information about the student with roll number 493. <?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> The following QueryStudent.java program gets all the elements of the root element ”class”. It the compares the value of roll number attribute with ”493”. If it matches, it prints all the student details using elementText() method. import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class QueryStudent { public static void main(String[] args) { try { //Creating SAXReader SAXReader reader = new SAXReader(); //Reading the XML file File inputFile = new File(“studentData.txt”); //Parsing the XML Document document = reader.read(inputFile); //Extracting the root Element RootElement = document.getRootElement(); System.out.println(“Root element :” + RootElement.getName()); List<Element> elements = RootElement.elements(); System.out.println(“—————————-“); for (Element ele : elements) { if(ele.attributeValue(“rollno”).equals(“493”)) { System.out.println(“nCurrent Element :” + ele.getName()); System.out.println(“Student roll no : ” + ele.attributeValue(“rollno”) ); System.out.println(“First Name : ” + ele.elementText(“firstname”)); System.out.println(“Last Name : ” + ele.elementText(“lastname”)); System.out.println(“First Name : ” + ele.elementText(“nickname”)); System.out.println(“Marks : ” + ele.elementText(“marks”)); } } } catch (DocumentException e) { e.printStackTrace(); } } } Output All the details of the student with roll number 493 are displayed. Root element :class —————————- Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta First Name : vinni Marks : 95 Print Page Previous Next Advertisements ”;
Modify XML Document
Java DOM4J Parser – Modify XML Document ”; Previous Next Java DOM4J API provides methods to modify XML documents. We might come across situations where we need to update few details in a large XML document. For example, an e-commerce website has many products whose price may vary on a daily or monthly basis. In such cases, modifying the already existing file makes the job simpler than to create the XML documents again. In this chapter, we are going to look at some examples to learn how to modify existing XML documents using DOM4J API. Modify XML Using Java DOM4J Parser Following are the steps to modify XML documents using Java DOM4J Parser − Step 1: Creating SAXReader object Step 2: Reading the XML file Step 3: Parsing the XML Step 4: Extracting the root Step 5: Modifying the elements Step 6: Creating a FileOutputStream Step 7: Writing the updated XML document into file Step 8: Printing the XML document Refer Parse XML Document chapter of this section for the first four steps. Step 5: Modifying the elements After extracting the root element in step 4, we can get any of its child elements by using the elements() method. We can modify already existing elements by editing their text content, changing attribute values, adding new attributes etc. Refer Create XML Document chapter of this section for the last three steps. Modify Text Content To modify text content of an element, we can use the method setText() to set the text content. It takes a string as an argument and updates the old text content with the new text content. This method is available in both Node and Element interfaces. Example In the following studentData.xml file, We need to update marks from 80 to 64 for the student with roll number 493. <?xml version=”1.0″ encoding=”UTF-8″?> <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>80</marks> </student> <student rollno=”593″> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> The following ModifyTextContent.java program reads the above studentData.xml file using SAXReader. Using elementIterator(“student”) method, we got all the student elements in an Iterator. We iterate all the elements to find the student with roll number 493 using attributeValue() method and updates the text content of marks element. import java.io.File; import java.io.FileOutputStream; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class ModifyTextContent { public static void main(String[] args) { try { //Creating SAXReader SAXReader reader = new SAXReader(); //Reading the XML file File inputFile = new File(“studentData.xml”); //Parsing the XML Document document = reader.read(inputFile); //Extracting the root Element RootElement = document.getRootElement(); //Modifying the elements Iterator<Element> students = RootElement.elementIterator(“student”); while(students.hasNext()) { Element student = students.next(); if(student.attributeValue(“rollno”).equals(“493”)) { Element marks = student.element(“marks”); marks.setText(“64”); } } //Creating a FileOutputStream FileOutputStream newFile = new FileOutputStream(“studentData.xml”); //Writing the updated 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 Marks for the student with roll number 493 is updated from 80 to 64. <?xml version=”1.0″ encoding=”UTF-8″?> <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>64</marks> </student> <student rollno=”593″> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> Add New Elements The addElement() method adds new elements to an existing XML document at the end of all the already existing child elements of that current element. We need to pass the tag name of the element as an argument. Similarly, the addText() method adds text content to the element. The addAttribute() adds new attribute to the current element. We need to pass attribute name and attribute value as arguments. The following AddNewElements.java program reads the studentData.xml file we have used in the previous example and uses the above methods to add information of a new student. import java.io.File; import java.io.FileOutputStream; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class AddNewElements { public static void main(String[] args) { try { //Creating SAXReader SAXReader reader = new SAXReader(); //Reading the XML file File inputFile = new File(“studentData.xml”); //Parsing the XML Document document = reader.read(inputFile); //Extracting the root Element RootElement = document.getRootElement(); //Modifying the elements Element student = RootElement.addElement(“student”).addAttribute(“rollno”, “693”); student.addElement(“firstname”).addText(“John”); student.addElement(“lastname”).addText(“Daniel”); student.addElement(“nickname”).addText(“Johny”); student.addElement(“marks”).addText(“78”); //Creating a FileOutputStream FileOutputStream newFile = new FileOutputStream(“studentData.xml”); //Writing the updated 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 file content after adding new student information is as follows − <?xml version=”1.0″ encoding=”UTF-8″?> <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>64</marks> </student> <student rollno=”593″> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> <student rollno=”693″> <firstname>John</firstname> <lastname>Daniel</lastname> <nickname>Johny</nickname> <marks>78</marks> </student> </class> Print Page Previous Next Advertisements ”;
Java DOM4J Parser
Java DOM4J Parser – Overview ”; Previous Next DOM4J is an open source, Java-based library to parse XML documents. It is a highly flexible and memory-efficient API. It is Java-optimized and uses Java collections like List and Arrays. DOM4J works with DOM, SAX, XPath, and XSLT. It can parse large XML documents with very low memory footprint. Environment Setup In order to use DOM4J parser, you should have dom4j-2.1.4.jar in your application”s classpath. You can download the jar file from here. When to Use DOM4J? You should use a DOM4J parser when − You need to know a lot about the structure of an XML 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. You are a Java developer and want to leverage Java-optimized parsing of XML. What is the Result of Parsing? When you parse an XML document with a DOM4J parser, you get the flexibility to get back a tree structure that contains all of the elements of your document without impacting the memory footprint of the application. DOM4J provides a variety of utility functions that you can use to examine the contents and structure of an XML document. XPath expressions can also be used to navigate through an XML document. Advantages Following are some advantages of DOM4J − Flexible and easily maintainable Open source, lightweight and quick API Random access of elements is possible DOM4J Interfaces The package ”org.dom4j” defines several Java interfaces. Here are the most commonly used interfaces − Interface Description Document Represents the entire XML document. A Document object is often referred to as a JDOM tree. Element Represents an XML element. Element object has methods to manipulate its child elements, text, attributes, and namespaces. Attribute Represents an attribute of an element. Attribute has methods to get and set the values of attributes. Node Represents Element, Attribute, or ProcessingInstruction. DOM4J methods When you are working with DOM4J, there are several methods you”ll often use. Some of them are as follows − Method Description SAXReader.read(xmlSource) Builds a DOM4J document from an XML source. Document.getRootElement() Returns the root element of an XML document. Element.node(index) Returns the XML node at a particular index in an element. Element.attributes() Returns all the attributes of an element. Node.valueOf(@Name) Returns the values of an attribute with the given name of an element. Print Page Previous Next Advertisements ”;
Query XML Document
Java XPath Parser – Query XML Document ”; Previous Next Java XPath is a Java API that helps us query XML documents using XPath expressions. Using XPath expressions, random access of elements is possible and hence we can select specific nodes from an XML document. This makes querying the documents more flexible. In this chapter, we have used XPath expressions with predicates such as ”/cars/carname/@company”, ”/class/student[@rollno = ”493”]” to query an XML document with various examples in detail. Query XML Using Java XPath Parser Following are the steps used while querying a document using Java XPath Parser − Step 1: Creating a DocumentBuilder Step 2: Reading the XML Step 3: Creating Document from file or Stream Step 4: Building XPath Step 5: Preparing and Evaluating XPath expression Step 6: Iterating over NodeList Step 7: Querying Elements Refer Parse XML Document chapter of this section for the first six steps. Step 7: Querying Elements Querying the XML document using XPath follows the same steps as parsing the XML document, but the only difference is seen in the way we prepare our XPath expressions. While querying, we query for a particular attribute or element. Querying by Element Names We can query the XML document based on their element names by specifying the element name inside the XPath expression. The XPath expression, ”root_element/element_name” retrieves all the nodes with the specified name inside the root element. Example The following cars.xml file has information about seven cars with the element name as ”carname” inside the root element ”cars”. We are going to query this XML file to check if there is ”Bentley 2”car. <?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 QueryByElements.java program reads the above cars.xml file and builds a document. Using the XPath expression ”/cars/carname”, we get the carname elements as nodes inside a nodeList. We iterate through the NodeList to find out Bentley 2 car. import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; public class QueryByElements { public static void main(String[] args) { try { //Creating DocumentBuilder DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Reading the XML File inputFile = new File(“cars.xml”); //Creating Document from file or Stream Document doc = dBuilder.parse(inputFile); //Building XPath XPath xPath = XPathFactory.newInstance().newXPath(); //Preparing and Evaluating XPath expression String expression = “/cars/carname”; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); //Iterating over NodeList boolean found = false; for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); //Querying the Elements if(nNode.getTextContent().equals(“Bentley 2”)) found=true; } 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 The output window displays that the Bentley 2 car is found. Bentley 2 car is found Querying by Attributes To query attributes inside elements, we use the XPath expression ”/root_element/element_name/@attr_name”. This expression fetches all the attributes with specified name of the specified element inside the root element. All these attributes are in the form of nodes inside the NodeList. Example 1 We use the same cars.xml file we have used in the previous example to count the total number of Bentley cars. We have used the expression, ”/cars/carname/@company” to get all the company attribute nodes and by checking it with ”Bentley”, we are incrementing the count variable. import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; public class QueryByAttributes { public static void main(String[] args) { try { //Creating a DocumentBuilder DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Reading the XML File inputFile = new File(“cars.xml”); //Creating Document from file or Stream Document doc = dBuilder.parse(inputFile); //Building XPath XPath xPath = XPathFactory.newInstance().newXPath(); //Preparing and Evaluating XPath expression String expression = “/cars/carname/@company”; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); //Iterating over NodeList int count=0; for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); //Querying the Elements if(nNode.getNodeValue().equals(“Bentley”)) count++; } System.out.println(“Number of Bentley cars found: ” + count); } catch (Exception e) { e.printStackTrace(); } } } Output The output window displays number of Bentley cars found in the XML document. Number of Bentley cars found: 3 Example 2 We need to query the following studentData.xml to get only the information related to the student with roll number 493. <?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 QueryXPathDemo.java program, we have parsed the above studentData.xml file and built a document. The XPath expression, ”/class/student[@rollno = ”493”]” is used to get that student element with roll number 493. import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; public class QueryXPathDemo { public static void main(String[] args) { try { //Creating a DocumentBuilder DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Reading the XML File inputFile = new File(“studentData.xml”); //Creating Document from file or Stream Document doc = dBuilder.parse(inputFile); //Building XPath XPath xPath = XPathFactory.newInstance().newXPath(); //Preparing and Evaluating XPath expression String expression = “/class/student[@rollno = ”493”]”; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); //Iterating over NodeList for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); System.out.println(“nCurrent Element :” + nNode.getNodeName()); //Getting student info with roll number 493 if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println(“Student roll no : ” + eElement.getAttribute(“rollno”)); System.out.println(“First Name : ” + eElement .getElementsByTagName(“firstname”) .item(0) .getTextContent()); System.out.println(“Last Name : ” + eElement .getElementsByTagName(“lastname”) .item(0) .getTextContent()); System.out.println(“Nick Name : ” + eElement .getElementsByTagName(“nickname”) .item(0) .getTextContent()); System.out.println(“Marks : ” + eElement .getElementsByTagName(“marks”) .item(0) .getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } } } The output window displays the information of the student with roll number 493. Output Current
Parse XML Document
Java DOM4J Parser – Parse XML Document ”; Previous Next Java DOM4J parser is an API in Java to parse XML documents. It creates DOM4J document from a built-in SAX parser or a DOM parser. After getting the document, we can retrieve the information of elements and attributes using the built-in methods of DOM4J Document and Element interfaces. In this chapter, we have used getRootElement() to extract root element of the document and the elements() method to get all of its child elements. Parse XML Using Java DOM4J Parser Following are the steps used while parsing a document using Java DOM4J Parser − Step 1: Creating SAXReader object Step 2: Reading the XML file Step 3: Parsing the XML Step 4: Extracting the root Step 5: Retrieving Elements Step 1: Creating SAXReader object The SAXReader class is used to create a DOM4J document from an XML file or stream. It has its own built-in SAX parser to parse the file. We create a SAXReader object as follows − SAXReader reader = new SAXReader(); Step 2: Reading the XML file To read XML content as a string, we can use StringBuilder class and later convert it into a ByteStream to create XML document. If XML content is available in the form of a file, we can read it using File class of java.io as follows − File inputFile = new File(“src/input.txt”); Step 3: Parsing the XML To parse the XML file, we have created SAXReader object in step 1. Using the read() method of SAXReader, we create DOM4J document by passing the file we read in step 2 as an argument as follows − Document document = reader.read(inputFile); Step 4: Extracting the Root The root element needs to be extracted from DOM4J document to obtain any information of elements. Using the getRootElement() method of Document interface we obtain the root element as follows − Element RootElement = document.getRootElement(); Step 5: Retrieving Elements After we have followed the first four steps, we now have the root element to obtain the information of its child elements. Now, we are going to perform some tasks such as retrieving the root, retrieving attributes and retrieving element text of an XML document with examples. Retrieving the Root The getRootElement() method of Document interface returns the root element of the document in the form of an Element object. To get the name of the element, we use getName() method of Element interface. It returns the name of the element in the form of a String. Example The studentData.xml file we need to parse is as follows − <?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> The RetrieveRoot.java program reads the above studentData.xml file using a SAXReader and obtains a DOM4J document. After getting the document, we use getRootElement() method to extract the root. import java.io.File; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class RetrieveRoot { public static void main(String[] args) { try { //Creating SAXReader SAXReader reader = new SAXReader(); //Reading the XML file File inputFile = new File(“studentData.xml”); //Parsing the XML Document document = reader.read(inputFile); //Extracting the root Element RootElement = document.getRootElement(); //Printing the Root Element Name System.out.println(“Root element Name :” + RootElement.getName()); } catch(Exception e) { e.printStackTrace(); } } } Output The root element name, ”class” is displayed on the output screen. Root element Name :class Retrieving Attributes The attributeValue() method of Element interface retrieves the value of the specified attribute in the form of a String. If there is no such attribute for that element, it returns null. If there is no value specified for the attribute, it returns an empty string. Example The following RetrieveAttributes.java program uses the attributeValue() method and retrieves all the roll numbers of student elements. import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class RetrieveAttributes { public static void main(String[] args) { try { //Creating SAXReader SAXReader reader = new SAXReader(); //Reading the XML file File inputFile = new File(“studentData.xml”); //Parsing the XML Document document = reader.read(inputFile); //Extracting the root Element RootElement = document.getRootElement(); //Iterating over the List List<Element> elements = RootElement.elements(); System.out.println(“Student Roll numbers – “); for (Element ele : elements) { System.out.println(ele.attributeValue(“rollno”) ); } } catch(Exception e) { e.printStackTrace(); } } } All the student roll numbers are displayed on the output screen. Output Student Roll numbers – 393 493 593 Retrieving Element Text The elements() method of Element interface returns the list of Elements contained in it. The elementText() method of Element interface returns the text content of the element in the form of a string. import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class DemoParse { public static void main(String[] args) { try { //Creating SAXReader SAXReader reader = new SAXReader(); //Reading the XML file File inputFile = new File(“studentData.xml”); //Parsing the XML Document document = reader.read(inputFile); //Extracting the root Element RootElement = document.getRootElement(); System.out.println(“Root Element: ” + RootElement.getName()); List<Element> elements = RootElement.elements(); System.out.println(“———————————“); //Iterating over the List for (Element ele : elements) { System.out.println(“nCurrent Element :” + ele.getName()); System.out.println(“Student roll no : ” + ele.attributeValue(“rollno”) ); System.out.println(“First Name : ” + ele.elementText(“firstname”)); System.out.println(“Last Name : ” + ele.elementText(“lastname”)); System.out.println(“First Name : ” + ele.elementText(“nickname”)); System.out.println(“Marks : ” + ele.elementText(“marks”)); } } catch (DocumentException e) { e.printStackTrace(); } } } Output All the information of students is displayed on the output screen. Root Element: class ——————————— Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad First Name : dinkar Marks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta First Name : vinni Marks : 95 Current Element :student Student roll no : 593 First Name : jasvir Last Name : singn First Name : jazz Marks : 90 Print Page Previous
Create XML Document
Java StAX Parser – Create XML Document ”; Previous Next Java StAX parser is a Java API that provides interfaces to create XML documents. There are cursor APIs such as XMLStreamWriter and Iterator APIs such as XMLEventWriter to create XML documents. In this chapter, we are going to use XMLStreamWriter to create XML documents. This interface has methods such as writeStartDocument(), writeStartElement(), writeCharacters() etc., to write XML content. Create XML using Java StAX parser We can create an XML document in Java using StAX parser through following steps − Step 1: Creating XMLStreamWriter object Step 2: Writing the XML document Step 3: Creating XMLStreamReader object Step 4: Writing the content into file Step 5: Testing the output using console Step 1: Creating XMLStreamWriter object The XMLOutputFactory is an abstract class which is used to create XMLEventWriters and XMLStreamWriters. We can either use XMLEventWriter or XMLStreamWriter objects to write XML documents. The createXMLStreamWriter() method of XMLOutputFactory creates an XMLStreamWriter object and the argument can be a Writer, OutputStream or any JAXP result. Here, we have created an XMLStreamWriter that writes to a Writer stream. XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xMLStreamWriter = xMLOutputFactory.createXMLStreamWriter(Writer stream); Step 2: Writing the XML document The XMLStreamWriter interface has many methods that specify how to write an XML document. They are self explanatory and does not return anything, but writes the content to the Writer. Following are the most commonly used methods of XMLStreamWriter interface − xMLStreamWriter.writeStartDocument(); xMLStreamWriter.writeStartElement(“cars”); xMLStreamWriter.writeCharacters(“Ferrari”); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeEndDocument(); Step 3: Creating XMLStreamReader object The XMLInputFactory is an abstract class for getting streams. Using createXMLStreamReader() method, we can create an XMLStreamReader object that allows us to read the InputStream specified. It gives forward, read-only access to the InputStream of XML data. XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = factory.createXMLStreamReader(InputStream stream); Step 4: Writing the content into file The transform() function of Transformer class tranforms the XML source to result. Source can be of type DOMSource, SAXSource, StAXSource or StreamSource and result can be of type DOMResult, SAXResult, StAXResult or StreamResult. To create Transformer object, we create an instance of TransformerFactory. Here, source is of type StAXSource and result is of type StreamResult. We can create a new File object and pass this as an argument to StreamResult object. TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, result); Step 5: Testing the output using console We can print the file content on the console by passing ”System.out” as an argument for StreamResult. The transform() method of Transformer class converts the source into StreamResult and writes it on the console. Another way of printing the result is by simply converting the Writer object we have used for XMLStreamWriter into a String and printing that string on the console. StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); Creating Basic XML file The writeStartDocument() method writes the XML declaration with default version number as 1.0 and encoding as utf-8. The writeStartElement(“element_name”) method opens a new start tag with the specified argument name as the name of the element. The scope gets closed once we specify corresponding EndElement. The writeCharacters(“text_content”) method appends the specified text content to the Element. Example Here is the basic XML file we want to create − <?xml version=”1.0″ ?> <cars>Ferrari</cars> The CreateBasicXML.java program creates cars.xml file using XMLStreamWriter class. We have used the methods writeStartDocument() to write the XML declaraction, writeStartElement(“cars”) to write the new Element named, “cars” and writeCharactrs(“Ferrari”) to write the text content. We have used writeEndElement() and writeEndDocument() methods to close the scopes correctly. import java.io.ByteArrayInputStream; import java.io.File; import java.io.StringWriter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; public class CreateBasicXML { public static void main(String[] args) throws TransformerException { try { //creating XMLStreamWriter XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance(); StringWriter stringWriter = new StringWriter(); XMLStreamWriter xMLStreamWriter = xMLOutputFactory.createXMLStreamWriter(stringWriter); //Writing the XML document xMLStreamWriter.writeStartDocument(); xMLStreamWriter.writeStartElement(“cars”); xMLStreamWriter.writeCharacters(“Ferrari”); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeEndDocument(); xMLStreamWriter.flush(); xMLStreamWriter.close(); //Creating XMLStreamReader object String xmlString = stringWriter.getBuffer().toString(); ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes(“UTF-8”)); stringWriter.close(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = factory.createXMLStreamReader(input); //writing the content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StAXSource source = new StAXSource(streamReader); StreamResult result = new StreamResult(new File(“D:\cars.xml”)); transformer.transform(source, result); //Testing the output using console System.out.println(xmlString); } catch (Exception e) { e.printStackTrace(); } } } Output The XML document we have written using XMLStreamWriter is displayed as follows − <?xml version=”1.0″ ?><cars>Ferrari</cars> Creating XML file with Attributes The writeAttribute(“attr_name”,”attr_value”) method appends the attribute to the current element. It should be written between writeStartElement() and witeEndElement() methods. If this method is placed incorrectly out of scope of an element, it throws IllegalStateException error. Example We have to create the following cars.xml file − <cars> <supercars company=”Ferrari”> <carname type=”formula one”>Ferrari 101</carname> <carname type=”sports”>Ferrari 202</carname> </supercars> </cars> In the following CreateAttributes.java program, we have created two carname elements under supercar element along with attributes. import java.io.ByteArrayInputStream; import java.io.File; import java.io.StringWriter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stax.StAXSource; public class CreateAttributes { public static void main(String[] args) throws TransformerException { try { //creating XMLStreamWriter XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance(); StringWriter stringWriter = new StringWriter(); XMLStreamWriter xMLStreamWriter = xMLOutputFactory.createXMLStreamWriter(stringWriter); //Writing the XML document xMLStreamWriter.writeStartDocument(); xMLStreamWriter.writeStartElement(“cars”); xMLStreamWriter.writeStartElement(“supercars”); xMLStreamWriter.writeAttribute(“company”, “Ferrari”); xMLStreamWriter.writeStartElement(“carname”); xMLStreamWriter.writeAttribute(“type”, “formula one”); xMLStreamWriter.writeCharacters(“Ferrari 101”); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeStartElement(“carname”); xMLStreamWriter.writeAttribute(“type”, “sports”); xMLStreamWriter.writeCharacters(“Ferrari 202”); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeEndDocument(); xMLStreamWriter.flush(); xMLStreamWriter.close(); //Creating XMLStreamReader object String xmlString = stringWriter.getBuffer().toString(); ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes(“UTF-8”)); stringWriter.close(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = factory.createXMLStreamReader(input); //writing the content into XML file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StAXSource source = new StAXSource(streamReader); StreamResult result = new StreamResult(new File(“D:\cars.xml”)); transformer.transform(source, result); //Testing the output using console System.out.println(xmlString); } catch (Exception e) { e.printStackTrace(); } } } Output The output window displays the XML content generated using XMLStreamWriter. <?xml version = “1.0” encoding = “UTF-8” standalone = “no”?> <cars> <supercars company = “Ferrari”> <carname type = “formula one”>Ferrari 101</carname> <carname type = “sports”>Ferrari 202</carname> </supercars> </cars> Print Page