Java XML Parsers ”; Previous Next Java has various XML parsers that support object type and event type standards. We can read, create, query and modify the XML documents using these APIs. APIs provide interfaces that represent the XML documents, methods to retrieve and modify the elements and attributes in XML documents. XML Parsers XML Parsers are the software libraries or packages that help client applications to interact with XML documents through interfaces. They are used to check the syntax of XML and validate it according to the DTD or XML schema. Parsers can be either document based or event based. Types of XML parsers Following are the two main types of XML parsers − DOM (Document Object Model) SAX (Simple API for XML) DOM (Document Object Model) DOM is proposed by W3C (World Wide Web Consortium). It is a tree based API and creates the entire XML document into a parse tree inside the main memory. Hence, it consumes more memory. DOM API provides interfaces to access, add and modify the documents that are independent of programming languages. DOM is suitable for small documents as it consumes more memory. We can both read and create documents using DOM APIs. SAX (Simple API for XML) SAX is an event based API. It will not load the entire document. Instead, it loads small parts of XML file. SAX is a read-only API, we cannot create XML documents using SAX. It is used to process large XML documents as it consumes less memory. Java XML Parsers The JAXP (Java API for XML Processing) APIs provide the standard interfaces to process XML documents in Java applications. It has interfaces that support both DOM and SAX standards. The below table describes various XML parsers and their relative classes or interfaces in java. Parser Description Class/Interface DOM Parser DOM parser represents an XML file as tree structure inside main memory. DOM provides interfaces to access and modify XML documents. DocumentBuilder SAX Parser SAX parser parses an XML document based on events and is used only for reading. The entire file is not loaded into the main memory. SaxParser JDOM Parser JDOM parser is an open source API that supports DOM, SAX, XSLT and XPath. It integrates with both DOM and SAX. DOMBuilder, SAXBuilder, StAXEventBuilder, StAXStreamBuilder, StAXStreamWriter StAX Parser StAX parser is a JAVA based streaming API and it is a pull-parsing model to read and write XML documents. XMLEventReader, XMLEventWriter DOM4J Parser DOM4J parser is a java based library that uses Java Collections framework to efficiently access and modify XML documents. DOMReader, DOMWriter, SAXReader, SAXWriter XPath Parser XPath parser parses the XML document based on expressions to access and modify nodes. XPath Print Page Previous Next Advertisements ”;
Category: java Xml
Parse XML Document
Java JDOM Parser – Parse XML Document ”; Previous Next Java JDOM Parser is an open source API in Java that has classes and methods to parse XML documents. JDOM provides random access of XML elements as it creates a tree document structure inside the memory using DOMBuilder or SAXBuilder. In this chapter, we are going to see how to build a JDOM document from an XML file using a SAX Parser. Parse XML Using JDOM Parser Following are the steps used while parsing a document using JDOM Parser − Step 1: Creating a SAXBuilder Object Step 2: Reading the XML Step 3: Parsing the XML Document Step 4: Retrieving the Elements Step 1: Creating a SAXBuilder Object JDOM document is build using a SAX Parser as follows − SAXBuilder saxBuilder = new SAXBuilder(); We can also create JDOM document using an already existing DOM org.w3c.dom.Document as follows − DOMBuilder domBuilder = new DOMBuilder(); Step 2: Reading the XML An XML file is taken into a File object as follows − File xmlFile = new File(“input.xml”); We can also take XML content using StringBuilder object. Later, we can convert it into bytes for parsing. StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<?xml version=”1.0″?> <rootElement></rootElement>”); ByteArrayInputStream input = new ByteArrayInputStream( xmlBuilder.toString().getBytes(“UTF-8”)); Step 3: Parsing the XML Document Using build() function, we parse an XML file or input stream. It builds the JDOM document from the given file or input stream. It throws JDOMException and IOException when there are errors in parsing the document. Document document = saxBuilder.build(input); Step 4: Retrieving the Elements After following the first three steps, we have successfully build JDOM document from our XML file or stream. We can now use methods available in Document and Element classes to obtain all the related information from the document. Retrieving Root Element The method getRootElement() of Document interface returns the root element of the document in the form of an Element object. The getName() method on Element object returns the name of the element in the form of a String. Example The following RetrieveRootElement.java program takes XML content in a StringBuilder object. It is then converted into bytes and parsed using build() function. It retrieves the root element and prints the name of the root element. import java.io.ByteArrayInputStream; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; public class RetrieveRootElement { public static void main(String args[]) { try { //Creating a SAXBuilder Object SAXBuilder saxBuilder = new SAXBuilder(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<class></class>”); ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); //Parsing the XML Document Document document = saxBuilder.build(input); //Retrieving the Root Element Name Element root_element = document.getRootElement(); System.out.println(“Root Element Name : ” + root_element.getName()); } catch (Exception e) { e.printStackTrace(); } } } Output The root element name, “class” is printed on the output screen. Root Element Name : class Retrieving Child Elements To retrieve child elements of an element, getChildren() method is used on the Element object. It returns the child elements in the form of a list. This list contains all the child elements in the of Element objects. To retrieve text content of an element, getText() method is used on the Element object. It returns the content between the opening and closing tags of an Element. Example Let us add three student child elements to our class element and save this file as student.xml. The name of the student is mentioned in the text content of each student element. <?xml version = “1.0”?> <class> <student>dinkar</student> <student>Vaneet</student> <student>jasvir</student> </class> Now, the following java program reads the student.xml file and retrieves all the child elements along with their text content. import java.io.File; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; public class RetrievingChildElements { public static void main(String[] args) { try { //Creating a SAXBuilder Object SAXBuilder saxBuilder = new SAXBuilder(); //Reading the XML File inputFile = new File(“student.xml”); //Parsing the XML Document Document document = saxBuilder.build(inputFile); //Retrieving Root Element Element RootElement = document.getRootElement(); System.out.println(“Root element :” + RootElement.getName()); //Retrieving Child Elements List<Element> studentList = RootElement.getChildren(); System.out.println(“—————————-“); for (int temp = 0; temp < studentList.size(); temp++) { Element student = studentList.get(temp); System.out.println(“nCurrent Element :” + student.getName()); System.out.println(“Text Content :” + student.getText()); } } catch(Exception e) { e.printStackTrace(); } } } Output All the three child elements are displayed with their text content. Root element :class —————————- Current Element :student Text Content :dinkar Current Element :student Text Content :Vaneet Current Element :student Text Content :jasvir Retrieving Attributes The getAttribute(“attr_name”) method on an Element object takes attribute name as an argument and retrieves the attribute in the form of Attribute object. If there is no such attribute in an element, it returns null. The getValue() method on an Attribute object retrieves the value of the attribute as textual content. Example To student.xml file, let us add some child elements to student element along with the attribute, “rollno”. Now, let us try to retrieve all this information using JDOM parser API. <?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 RetrievingAttributes.java program, we have first collected all the child elements in an Element list and then used getChild() method to get the details of each child inside the student element. import java.io.File; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; public class RetrievingAttributes { public static void main(String[] args) { try { //Creating a SAXBuilder Object SAXBuilder saxBuilder = new SAXBuilder(); //Reading the XML File inputFile = new File(“student.xml”); //Parsing the XML Document Document document = saxBuilder.build(inputFile); //Retrieving Root Element Element RootElement = document.getRootElement(); System.out.println(“Root element :” + RootElement.getName()); //Retrieving Child Elements and Attributes List<Element> studentList = RootElement.getChildren(); System.out.println(“—————————-“); for (int temp = 0; temp < studentList.size(); temp++) { Element student = studentList.get(temp); System.out.println(“nCurrent Element :” + student.getName()); Attribute attribute = student.getAttribute(“rollno”); System.out.println(“Student roll no : ” + attribute.getValue() ); System.out.println(“First Name : ” + student.getChild(“firstname”).getText()); System.out.println(“Last Name : ” + student.getChild(“lastname”).getText());
Parse XML Document
Java StAX Parser – Parse XML Document ”; Previous Next The Java StAX parser API has classes, methods and interfaces to parse XML documents in the form of events. It is a pull based API that gives the client program more privilege to access the events only if required. In this chapter, we are going to see how to parse an XML documents in Java using StAX parser API in detail. Parse XML Using Java StAX Parser Following are the steps used while parsing a document using Java StAX Parser − Step 1: Creating XMLInputFactory instance Step 2: Reading the XML Step 3: Parsing the XML Step 4: Retrieving the Elements Step 1: Creating XMLInputFactory instance The XMLInputFactory class is an abstract class that is used to get input streams. To create a new instance of an XMLInputFactory, we use newInstance() method. If the instance of this factory cannot be loaded, it throws an error named, “FactoryConfigurationError”. XMLInputFactory factory = XMLInputFactory.newInstance(); Step 2: Reading the XML The FileReader class is used to read streams of characters from the input file. The following statement throws “FileNotFoundException” if the file can”t be found or if the file can”t be read for some reason. FileReader fileReader = new FileReader(“src/input.txt”); Instead of reading XML content from the file, we can also get the content in the form of a string and convert it into bytes as follows − StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<class>xyz</class>”); ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); Step 3: Parsing the XML To parse XML events, we create XMLEventReader from the XMLInputFactory object by passing either the FileReader object or the input stream object. If the creation of XMLEventReader is not successful, it throws XMLStreamException. XMLEventReader eventReader = factory.createXMLEventReader(input); Step 4: Retrieving the Elements The nextEvent() method of XMLEventReader returns the next XML event in the form of XMLEvent object. The XMLEvent has methods to return events as startElement, endElement and Characters. XMLEvent event = eventReader.nextEvent(); Retrieving Element Name To retrieve Element name, we should first get the Element from the XML document. When the event is of type XMLStreamConstants.START_ELEMENT, the asStartElement() on an XMLEvent object, retrieves the Element in the form of a StartElement object. The getName() method of StartElement returns the name of the Element in the form of a String. Example The RetrieveElementName.java program takes the XML content in a StringBuilder object and convert it into bytes. The obtained InputStream is used to create XMLEventReader. The Element is accessed using the events notified by the parser. import java.io.ByteArrayInputStream; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class RetrieveElementName { public static void main(String args[]) { try { //Creating XMLInputFactory instance XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<class>xyz</class>”); ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); //Parsing the XML XMLEventReader eventReader = factory.createXMLEventReader(input); //Retrieving the Elements while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if(event.getEventType()==XMLStreamConstants.START_ELEMENT) { StartElement startElement = event.asStartElement(); System.out.println(“Element Name: ” + startElement.getName()); } } } catch(Exception e) { e.printStackTrace(); } } } Output The name of the Element is displayed on the output screen. Element Name: class Retrieving Text Content To retrieve text content of an element, asCharacters() method is used on XMLEvent object. When the event is of type XMLStreamConstants.CHARACTERS, only then we can use asCharacters() method. This method returns the data in the of Characters object. The getData() method is used to get the text content in the form of a String. Example In the previous example, we have taken XML content as an Input Stream. Now, let us take input by reading from a file by saving the following XML content in a file named, classData.xml <class>xyz</class> In the following RetrievingTextContent.java program, we have read the classData.xml file using a FileReader object and passed as an input to XMLEventReader. Using, XMLEvent object, we have obtained the text content of the Element. 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 RetrievingTextContent { public static void main(String args[]) { try { //Creating XMLInputFactory instance XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading the XML FileReader fileReader = new FileReader(“classData.xml”); //Parsing the XML XMLEventReader eventReader = factory.createXMLEventReader(fileReader); //Retrieving the Elements while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if(event.getEventType()==XMLStreamConstants.CHARACTERS) { Characters characters = event.asCharacters(); System.out.println(“Text Content : “+ characters.getData()); } } } catch(Exception e) { e.printStackTrace(); } } } Output The text content of the element is displayed on the output screen. Text Content : xyz Retrieving Attributes The getAttributes() method of StartElement interface returns a readonly Iterator of attributes declared on this element. If there are no attributes declared on this element, it returns an empty iterator. The getValue() function on Attribute interface returns the value of the attribute in the form of a String. Example The following classData.xml has the information of three students along with their roll numbers as attributes. Let us retrieve this information using StAX API in Java. <?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 RetrieveAttributes.java program, we have used switch case statements for START_ELEMENT, CHARACTERS and END_ELEMENT XMLStreamConstants to access all the information of elements. import java.io.FileNotFoundException; 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.XMLStreamException; 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 RetrievingAttributes { public static void main(String[] args) { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; try { //Creating XMLInputFactory instance XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading the XML FileReader fileReader = new FileReader(“classData.xml”); //Parsing the XML XMLEventReader eventReader = factory.createXMLEventReader(fileReader); //Retrieving the Elements 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”)) { System.out.println(“Start Element : student”); Iterator<Attribute> attributes = startElement.getAttributes(); String rollNo = attributes.next().getValue(); System.out.println(“Roll No : ” + rollNo); } else if (qName.equalsIgnoreCase(“firstname”)) { bFirstName = true; } else if (qName.equalsIgnoreCase(“lastname”))
Parse XML Document
Java XPath Parser – Parse XML Document ”; Previous Next Java XPath parser is an API in Java to parse XML documents using XPath expressions and functions. It helps us to traverse through the entire XML document and obtain elements as nodes inside a NodeList. The package ”javax.xml.xpath” provides the API for the evaluation of XPath expressions. In this chapter, we will see how to traverse through all the nodes in an XML document. Parse XML Using Java XPath Parser Following are the steps used while parsing 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: Retrieving Elements Step 1: Create a DocumentBuilder The DocumentBuilderFactory is a factory API that is used to create DocumentBuilder objects. The newDocumentBuilder() method of DocumentBuilderFactory returns a DocumentBuilder object as follows − DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Step 2: Reading the XML The FileReader class is used to read streams of characters from the input file. The following statement throws “FileNotFoundException” if the file can”t be found or if the file can”t be read for some reason. FileReader fileReader = new FileReader(“src/input.txt”); Instead of reading XML content from the file, we can also get the content in the form of a string and convert it into bytes as follows − StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<class>xyz</class>”); ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); Step 3: Create a Document from a file or stream The DocumentBuilder object created in the first step is used to create a document from the input file or input stream. The parse() method takes file or stream as an argument and returns a Document object as follows − Document doc = builder.parse(input); Step 4: Building XPath To parse XML document using XPath, we need to build a newXPath using newXPath() method of XPathFactory. This method returns a new XPath as follows − XPath xPath = XPathFactory.newInstance().newXPath(); Step 5: Preparing and Evaluating XPath expression As we have discussed in the previous chapter, XPath has expressions that help us retrieve information from the XML documents, here we need to create one such expression based on the requirement and evaluate it. The evaluate() method returns the result of the expression as a NodeList as follows − String expression = “/class/student”; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); Step 6: Iterating over NodeList The NodeList we get in step 5 is now iterated to examine each node and retrieve information accordingly. Here, we have used a for loop to iterate over the NodeList, you can use any loop of your choice. for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); … } Step 7: Retrieving Elements After following the above six steps, we obtain the elements in the form of nodes. By using the methods of interfaces available in DOM, we can retrieve the necessary elements and attributes. Retrieve Root Element To retrieve root element from the XML document, we have the XPath expression ”/”. Using this expression and by evaluating this, we get the NodeList with just a single Node. The getNodeName() method of Node interface retrieves the name of the node as a String object and the getTextContent() method returns the text content of the node as a String. Example In the following example, we have taken XML content as a StringBuilder object and parsed it using parse() function. We have only a single element, which is obviously the root and we have text content as ”xyz class”. Using the methods discussed above we retrieve the information of root element. import java.io.ByteArrayInputStream; 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 RetrieveRoot { public static void main(String[] args) { try { //Creating a DocumentBuilder DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<class>xyz class</class>”); ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); //Creating Document from file or Stream Document doc = dBuilder.parse(input); //Building XPath XPath xPath = XPathFactory.newInstance().newXPath(); //Preparing and Evaluating XPath expression String expression = “/”; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODE); //Iterating over NodeList for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); //Retrieving Root Element System.out.println(“Root Element Name: ” + node.getNodeName()); System.out.println(“Text Content: ” + node.getTextContent()); } } catch(Exception e) { e.printStackTrace(); } } } Output The root element name and text content are displayed on the console. Root Element Name: class Text Content: xyz class Retrieving Attributes The NodeList we get after evaluating the XPath expression has nodes with different node types. We can convert those nodes into Elements if the node type is equal to ”ELEMENT_NODE”. The getAttribute(“attribute_name”) method of Element interface is used to retrieve the value of attribute in the form of a String. Example The following studentData.xml file has information of three students. We are going to retrieve this information using XPath parser library in Java. The class element is the root element with three student child elements. Let us see how to use XPath library in java to retrieve the infromation of three students. <?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 RetrieveAttributes.java program, we have parsed the student.xml file and built a document. The expression ”/class/student” is used to get all the ”student” nodes inside the ”class” node into a NodeList. The NodeList is then iterated and got the information of each student. 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 RetrieveAttributes { public static void main(String[] args) { try { //Creating a DocumentBuilder DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Reading the XML File
Modify XML Document
Java SAX Parser – Modify XML Document ”; Previous Next Java SAX parser is a Java API that can be used to parse and modify XML documents. To modify any XML document using SAX parser, We have to store the data in any data structure because we cannot go back as it has only forward read-only access. In this chapter, we are going to see how to read and modify existing XML document in detail. Modify XML Using Java SAX Parser 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: Writing the updated content into file Refer Parse XML Document chapter of this section for the first five steps. Step 6: Writing the Updated Content into File The updated content can be written into the file using write() method of FileWriter object as follows − FileWriter filewriter = new FileWriter(“newfile.xml”); filewriter.write(“content_here”); Modifying XML File SAX parser will not provide random access to elements as DOM provides. We can implement the call back methods in Handler class that implements DefaultHandler to create and add new elements to the already exisiting XML document. Example In this example, we are going to see how to modify studentData.xml file by adding result element to the student element. Here is the sudentData.xml file that we need to modify by appending <Result>Pass<Result/> at the end of </marks> tag. <?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 ModifyXML.java program, we have created SAXParser object and parsed the input file. We have implemented the Handler class with the necessary call back methods and writeFile() method to write the updated content into the file. We have used an array of String to store and write the content to the file. import java.io.*; import org.xml.sax.*; import javax.xml.parsers.*; import org.xml.sax.helpers.DefaultHandler; //Implementing a Handler class class UserDemoHandler extends DefaultHandler { static String displayText[] = new String[1000]; static int numberLines = 0; static String indentation = “”; public void startDocument() { displayText[numberLines] = indentation; displayText[numberLines] += “<?xml version = “1.0” encoding = “”+ “UTF-8” + “”?>”; numberLines++; } public void processingInstruction(String target, String data) { displayText[numberLines] = indentation; displayText[numberLines] += “<?”; displayText[numberLines] += target; if (data != null && data.length() > 0) { displayText[numberLines] += ” ”; displayText[numberLines] += data; } displayText[numberLines] += “?>”; numberLines++; } public void startElement(String uri, String localName, String qualifiedName, Attributes attributes) { displayText[numberLines] = indentation; indentation += ” “; displayText[numberLines] += ”<”; displayText[numberLines] += qualifiedName; if (attributes != null) { int numberAttributes = attributes.getLength(); for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) { displayText[numberLines] += ” ”; displayText[numberLines] += attributes.getQName(loopIndex); displayText[numberLines] += “=””; displayText[numberLines] += attributes.getValue(loopIndex); displayText[numberLines] += ”””; } } displayText[numberLines] += ”>”; numberLines++; } public void characters(char characters[], int start, int length) { String characterData = (new String(characters, start, length)).trim(); if(characterData.indexOf(“n”) < 0 && characterData.length() > 0) { displayText[numberLines] = indentation; displayText[numberLines] += characterData; numberLines++; } } public void endElement(String uri, String localName, String qualifiedName) { indentation = indentation.substring(0, indentation.length() – 4) ; displayText[numberLines] = indentation; displayText[numberLines] += “</”; displayText[numberLines] += qualifiedName; displayText[numberLines] += ”>”; numberLines++; if (qualifiedName.equals(“marks”)) { startElement(“”, “Result”, “Result”, null); characters(“Pass”.toCharArray(), 0, “Pass”.length()); endElement(“”, “Result”, “Result”); } } public void writeFile(FileWriter filewriter) throws IOException { for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) { filewriter.write(displayText[loopIndex].toCharArray()); filewriter.write(”n”); System.out.println(displayText[loopIndex].toString()); } filewriter.close(); } } public class ModifyXML extends DefaultHandler { public static void main(String args[]) { try { //Creating SAXParser object SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); //Reading the XML File inputFile = new File(“src/input.txt”); //Creating object for Handler class UserDemoHandler userHandler = new UserDemoHandler(); //Parsing the XML saxParser.parse(inputFile, userHandler); //Writing the updated content into file FileWriter filewriter = new FileWriter(“src/newfile.xml”); userHandler.writeFile(filewriter); } catch (Exception e) { e.printStackTrace(System.err); } } } The output window displays the updated content of the XML document after adding result element to each student element. <?xml version = “1.0” encoding = “UTF-8”?> <class> <student rollno = “393”> <firstname> dinkar </firstname> <lastname> kad </lastname> <nickname> dinkar </nickname> <marks> 85 </marks> <Result> Pass </Result> </student> <student rollno = “493”> <firstname> Vaneet </firstname> <lastname> Gupta </lastname> <nickname> vinni </nickname> <marks> 95 </marks> <Result> Pass </Result> </student> <student rollno = “593”> <firstname> jasvir </firstname> <lastname> singn </lastname> <nickname> jazz </nickname> <marks> 90 </marks> <Result> Pass </Result> </student> </class> Print Page Previous Next Advertisements ”;
JDOM XML Parser
Java JDOM Parser – Overview ”; Previous Next JDOM is an open source, Java-based library to parse XML documents. It is typically a Java developer friendly API. It is Java optimized and it uses Java collections like List and Arrays. JDOM works with DOM and SAX APIs and combines the best of the two. It is of low memory footprint and is nearly as fast as SAX. Environment Setup In order to use JDOM parser, you should have jdom.jar in your application”s classpath. Download jdom-2.0.5.zip. When to Use JDOM parser? You should use a JDOM 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 JDOM 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. JDOM provides a variety of utility functions that you can use to examine the contents and structure of an XML document in case the document is well structured and its structure is known. Advantages Following are the advantages of JDOM parser − Developer friendly API. Flexible and easily maintainable. Lightweight and quick API Well integrates with DOM and SAX standards. JDOM classes JDOM defines several Java classes. Here are the most common classes − Class Description Document Represents an entire XML document. A Document object is often referred to as a DOM tree. Element Represents an XML element. Element object has methods to manipulate its child elements, its text, attributes, and namespaces. Attribute Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type. Text Represents the text of XML tag. Comment Represents the comments in a XML document. JDOM Methods When you are working with JDOM, there are several methods you”ll use often − Class Description SAXBuilder.build(xmlSource) Build the JDOM document from the xml source. Document.getRootElement() Get the root element of the XML. Element.getName() Get the name of the XML node. Element.getChildren() Get all the direct child nodes of an element. Node.getChildren(Name) Get all the direct child nodes with a given name. Node.getChild(Name) Get the first child node with the given name. Print Page Previous Next Advertisements ”;
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 ”;
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 ”;
Create XML Document
Java SAX Parser – Create XML Document ”; Previous Next Java SAX Parser is a read-only parser which is used to read the XML documents in a forward read-only manner. We cannot create XML documents using a SAX parser. It is better to use StAX parser for creating XML documents rather than using SAX parser. Please refer the Java StAX Parser section for the same. Print Page Previous Next Advertisements ”;