Java XML – Questions and Answers ”; Previous Next Java XML Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. Sr.No. Question/Answers Type 1 Java XML Interview Questions This section provides a huge collection of Java XML Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Java XML Online Quiz This section provides a great collection of Java XML Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Java XML Online Test If you are preparing to appear for a Java and Java XML Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Java XML Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;
Category: java Xml
Java XML – Useful Resources
Java XML – Useful Resources ”; Previous Next The following resources contain additional information on Java XML. Please use them to get more in-depth knowledge on this. Useful Video Courses Java Programming Course For Beginners Best Seller 146 Lectures 16.5 hours Karthikeya T More Detail Advanced Java Using Eclipse IDE: Learn JavaFX & Databases Most Popular 34 Lectures 7.5 hours Syed Raza More Detail Java Made Easy for Beginners, Testers, Selenium and Appium 249 Lectures 62 hours Arun Motoori More Detail Java SE 11 Programming: For Beginners Most Popular 123 Lectures 8.5 hours Lemuel Ogbunude More Detail Core Java Bootcamp Program With Hands-On Practice Featured 99 Lectures 17 hours Selfcode Academy More Detail Learn Java Programming For Beginners Featured 24 Lectures 5.5 hours Quaatso Learning More Detail Print Page Previous Next Advertisements ”;
Query XML Document
Java SAX Parser – Query XML Document ”; Previous Next Java SAX Parser is an API in java which can be used to query XML documents. To query large XML documents using event based APIs, we can use Java SAX parser API. The SAXParser API is present inside the javax.xml.parsers package. We can query any XML document by implementing the call back methods inside Handler class by inheriting DefaultHandler class which in turn inherits ContentHandler interface. Query XML using Java SAX parser We can query any XML document in Java using SAX parser through following steps − Step 1: Implementing a Handler class Step 2: Creating a SAXParser Object Step 3: Reading the XML Step 4: Creating object for Handler class Step 5: Parsing the XML Document Step 6: Querying the Elements Refer this chapter for the first five steps. Step 6: Querying the Elements The ContenHnadler and Attributes interfaces provide various methods which help us query elements and their attributes. For querying required information, We implement code inside our Handler class. Querying Elements by TextContent The characters() method is used to get the content of elements. The endDocument() function is called at the end of the document. We can use this method to perform some necessary actions that we need to do before closing our XML file. Example We need to query the following cars.xml file to find out whether there is “Bentley 2” car in the document. <?xml version = “1.0”?> <cars> <carname company=”Ferrari” >Ferrari 101</carname> <carname company=”Lamborghini”>Lamborghini 001</carname> <carname company=”Lamborghini”>Lamborghini 002</carname> <carname company=”Lamborghini”>Lamborghini 003</carname> <carname company=”Bentley”>Bentley 1</carname> <carname company=”Bentley”>Bentley 2</carname> <carname company=”Bentley”>Bentley 3</carname> </cars> In the following java program, we have implemented characters() and endDocument() methods inside UserHandler class. We have written the code to find Bentley cars inside the characters() function and the end result is printed using endDocument() method. import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; //Implementing UserHandler Class class UserHandler extends DefaultHandler { boolean found = false; public void characters(char[] ch, int start, int length) throws SAXException{ String textContent = new String(ch,start,length); if(textContent.equals(“Bentley 2”)) { found=true; } } public void endDocument() { if(found) System.out.println(“Bentley 2 car is found”); else System.out.println(“Bentley 2 car is not Found”); } } public class QueryXMLElements { public static void main(String args[]) { try { //Creating a DocumentBuilder Object SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); //Reading the XML File xmlFile = new File(“cars.xml”); //Creating UserHandler object UserHandler userHandler = new UserHandler(); //Parsing the XML Document saxParser.parse(xmlFile, userHandler); } catch(Exception e) { e.printStackTrace(); } } } The output displays that the Bentley car is found. Bentley 2 car is found Querying Elements by Attributes We can query the elements by their attributes using the Attributes interface. We get the list of attributes of an element as a last argument from the startElement() function. As discussed in the previous chapter, the getValue(“attr_name”) function is used to obtain the attribute value. Example Let us use our cars.xml file that we used in the previous example to count number of Bentley cars. This information can be obtained only through the attribute value. As the parser encounters an element, we are using getValue(“company”) to get the company attribute and incrementing the count if that company is Bentley. import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; //Implementing UserHandler Class class UserHandler extends DefaultHandler { int count=0; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String company = attributes.getValue(“company”); if(qName.equals(“carname”) && company.equals(“Bentley”)) { count++; } } public void endDocument() { System.out.println(“No. of Bentley cars found : ” + count); } } public class QueryXMLAttributes { public static void main(String args[]) { try { //Creating a DocumentBuilder Object SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); //Reading the XML File xmlFile = new File(“cars.xml”); //Creating UserHandler object UserHandler userHandler = new UserHandler(); //Parsing the XML Document saxParser.parse(xmlFile, userHandler); } catch(Exception e) { e.printStackTrace(); } } } The output is displayed when the endDocument() method is invoked. No.of Bentley cars found : 3 Print Page Previous Next Advertisements ”;
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 ”;
Query XML Document
Java DOM Parser – Query XML Document ”; Previous Next Java DOM parser is an API in java to parse and query XML documents. Using Java DOM parser, we can query large XML documents to get insights about our data. Manually, it is not easy to check the entire XML document to obtain related information. We can query XML elements by their tag name using getElementsByTagName() method. To query based on attribute value, getAttribute() method can be used. Query XML Using Java DOM Parser We can query any XML document in Java using DOM parser through following steps − Step 1: Creating a DocumentBuilder Object Step 2: Reading the XML Step 3: Parsing the XML Document Step 4: Querying the XML Document Refer this page for first three steps. Step4: Querying the XML Document After following the first three steps we can query the XML document according to our business requirements using DOM methods. Querying Elements by TagName We can query the XML elements by their tag name by using the method, getElementsByTagName(”carname”) on the Document interface. This method takes tag name in the form of a String and returns the list of nodes with the same tag name as a NodeList. The getTextContent() method of Node interface gives the text content inside the node in the form of a String. cars.xml The cars.xml file has seven <carname> elements inside the root element, <cars>. <?xml version = “1.0”?> <cars> <carname company=”Ferrari” >Ferrari 101</carname> <carname company=”Lamborghini”>Lamborghini 001</carname> <carname company=”Lamborghini”>Lamborghini 002</carname> <carname company=”Lamborghini”>Lamborghini 003</carname> <carname company=”Bentley”>Bentley 1</carname> <carname company=”Bentley”>Bentley 2</carname> <carname company=”Bentley”>Bentley 3</carname> </cars> Query XML Elements In the following program, we got all the nodes into a nodeList and then iterated each node to get the text content and checked if that equals to “Bentley 2”. If it is found, we are printing on the console that it is found or else we are printing not found. import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import java.io.File; public class QueryXMLDemo { public static void main(String argv[]) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Reading the XML file File inputFile = new File(“cars.xml”); //Parsing the XML Document Document doc = dBuilder.parse(inputFile); //checking “Bentley 2” car int flag=0; NodeList nList = doc.getElementsByTagName(“carname”); for(int i=0;i<nList.getLength();i++) { if(nList.item(i).getTextContent().equals(“Bentley 2”)) { System.out.println(“Bentley 2 car is “+”found”); flag=1; break; } } if(flag==0) { System.out.println(“Bentley 2 car is “+”not found”); } } catch (Exception e) {e.printStackTrace();} } } Output Since, “Bentley 2” car is present, it displays that it is found. Bentley 2 car is found Querying Elements by Attributes We can query the elements by their attributes using the method getAttribute(“Attribute_name”) of Element interface. This method takes attribute name as an argument and returns value of the attribute. Example In the following program, we have parsed cars.xml file and incremented the count variable every time “Bentley” is found. import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Element; import java.io.File; public class QueryXMLAttributes { public static void main(String argv[]) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Reading the XML file File inputFile = new File(“cars.xml”); //Parsing the XML Document Document doc = dBuilder.parse(inputFile); //counting Bentley cars int count=0; NodeList nList = doc.getElementsByTagName(“carname”); for(int i=0;i<nList.getLength();i++) { Element ele = (Element) nList.item(i); if(ele.getAttribute(“company”).equals(“Bentley”)) { count++; } } System.out.println(“No of Bentley cars: “+ count); } catch (Exception e) {e.printStackTrace();} } } Output The above program counts the number of Bentley cars and displays on the console. No of Bentley cars: 3 Print Page Previous Next Advertisements ”;