Java DOM Parser – Parse XML Document ”; Previous Next Java DOM parser is a Java API to parse any XML document. Using the methods provided, we can retrieve root element, sub elements and their attributes using Java DOM parser. In this tutorial we have used the getTagName() method to retrieve the tag name of elements, getFirstChild() to retrieve the first child of an element and getTextContent() to get the text content of elements. Parse XML Using Java DOM parser Having discussed various XML parsers available in Java, now let us see how we can use DOM parser to parse an XML file. We use parse() method to parse an XML file. Before jumping into the example directly, let us see the steps to parse XML document using Java DOM parser − Step 1: Creating a DocumentBuilder Object Step 2: Reading the XML Step 3: Parsing the XML Document Step 4: Retrieving the Elements Step 1: Creating a DocumentBuilder Object DocumentBuilderFactory is a factory API to obtain parser to parse XML documents by creating DOM trees. It has ”newDocumentBuilder()” method that creates an instance of the class ”DocumentBuilder”. This DocumentBuilder class is used to get input in the form of streams, files, URLs and SAX InputSources. DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Step 2: Reading the XML Input can be of file type or stream type. To input an XML file, Create a file object and pass the file path as argument. File xmlFile = new File(“input.xml”); To get input in the form of stream, we have used StringBuilder class and appended the input string and later converted it into bytes. The obtained ByteArrayInputStream is given as input to the document. StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<?xml version=”1.0″?> <rootElement></rootElement>”); ByteArrayInputStream input = new ByteArrayInputStream( xmlBuilder.toString().getBytes(“UTF-8″)); Step 3: Parsing the XML Document DocumentBuilder created in above steps is used to parse the input XML file. It contains a method named parse() which accepts a file or input stream as a parameter and returns a DOM Document object. If the given file or input stream is NULL, this method throws an IllegalArgumentException. Document xmldoc = docBuilder.parse(input); Step4: Retrieving the Elements The Node and Element interfaces of the org.w3c.dom. package provides various methods to retrieve desired information about elements from the XML documents. This information includes element”s name, text content, attributes and their values. We have many DOM interfaces and methods to get this information. Retrieving Root Element Name XML document constitutes of many elements. In Java an XML/HTML document is represented by the interface named Element. This interface provides various methods to retrieve, add and modify the contents of an XML/HTML document. We can retrieve the name of the root element using the method named getTagName() of the Element interface. It returns the name of the root element in the form of a string. Since Element is an interface, to create its object we need to use the getDocumentElement() method. This method retrieves and returns the root element in the form of an object. Example In the following example we have passed a simple XML document with just one root element ”college” using StringBuilder class. Then, we are retrieving it and printing on the console. import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; public class RetrieveRootElementName { public static void main(String[] args) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<college></college>”); //Parsing the XML Document ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); Document xmldoc = docBuilder.parse(input); //Retrieving the Root Element Name Element element = xmldoc.getDocumentElement(); System.out.println(“Root element name is “+element.getTagName()); } catch (Exception e) { e.printStackTrace(); } } } Output The element name, ”college” is displayed on the output screen as shown below − Root element name is college Parsing Single Sub Element in XML We can parse a simple XML document with single element inside the root element. So far, we have seen how to retrieve the root element. Now, let us see how to get the sub element inside the root element. Since, we have only one sub element, we are using getFirstChild() method to retrieve it. This method is used with the root element to get its first child. It returns the child node in the form of a Node object. After retrieving the child node, getNodeName() method is used to get the name of the node. It returns the node name in the form of a string. To get the text content, we use getTextContent() method. It returns the text content in the form of a String. Example Let us see the following example where we have one root element and a sub element. Here, ”college” is the root element with ”department” as sub element. The ”department” element has text content, “Computer Science”. We are retrieving the name and text content of the sub element. import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; public class SingleSubElement { public static void main(String[] args) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<college><department>Computer Science</department></college>”); //Parsing the XML Document ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8”)); Document xmldoc = docBuilder.parse(input); //Retrieving the Root Element Element element = xmldoc.getDocumentElement(); //Retrieving the Child Node Node childNode = element.getFirstChild(); String childNodeName = childNode.getNodeName(); System.out.println(“Sub Element name : ” + childNodeName); //Retrieving Text Content of the Child Node “+ childNodeName); System.out.println(“Text content of Sub Element : “+childNode.getTextContent()); } catch (Exception e) { e.printStackTrace(); } } }
Category: java Xml
Java SAX Parser
Java SAX Parser – Overview ”; Previous Next Java SAX (Simple API for XML) is an event-based parser to parse XML documents. Unlike DOM parser, SAX parser does not create a parse tree. It will not load the entire document into memory, instead, it reads through the XML document and notifies the client program whenever it encounters elements, attributes, text content and other data items in the form of events. These events are handled by the methods implemented inside the Event Handler. What does SAX Parser do? A SAX Parser does the following to a client program − 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 SAX Parser? You should use a SAX 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). Advantages Following are some advantages of Java SAX Parser − Consumes less memory It is faster than DOM parser. Because, we need not wait for the entire document to get loaded in the memory. You can still process the XML documents larger than the system memory. Disadvantages Here are some of the disadvantages of Java SAX Parser − Random access to an XML document is not possible. Creating XML documents is not possible. If you want to keep track of data that the parser has seen or change the order of items, you must write the code and store the data on your own. ContentHandler Interface ContentHandler interface is the main interface in org.xml.sax package. Most of the application programs implement this interface to perform basic parsing events. These events include start and end of a document, start and end of the elements and character data. We must implement and register a Handler to perform any task in the XML document. There are built-in classes, namely, DefaultHandler, DefaultHandler2, ValidatorHandler that implement ContentHandler interface. We can use these classes to implement our user defined Handlers. This interface specifies the callback methods that the SAX parser uses to notify an application program of the components of the XML document that it has seen. Following are the methods of ContentHandler interface − Method Description void startDocument() Called at the beginning of a document. void endDocument() Called at the end of a document. void startElement(String uri, String localName, String qName, Attributes atts) Called at the beginning of an element. void endElement(String uri, String localName,String qName) Called at the end of an element. void characters(char[] ch, int start, int length) Called when character data is encountered. void ignorableWhitespace( char[] ch, int start, int length) Called when a DTD is present and ignorable whitespace is encountered. void processingInstruction(String target, String data) Called when a processing instruction is recognized. void setDocumentLocator(Locator locator)) Provides a Locator that can be used to identify positions in the document. void skippedEntity(String name) Called when an unresolved entity is encountered. void startPrefixMapping(String prefix, String uri) Called when a new namespace mapping is defined. void endPrefixMapping(String prefix) Called when a namespace definition ends its scope. Attributes Interface The Attributes interface is in the package org.xml.sax. This interface is for the list of XML attributes specified in an Element. Following are the most commonly used methods of Attributes interface − Method Description int getLength() Returns number of attributes. int getIndex(String qName) Returns the index of the attribute in the list, -1 if not present. String getQName(int index) Returns the attribute name by index, null if the index is out of bounds. String getType(int index) Returns the type (“CDATA”, “ID”, “IDREF”, etc.) of attribute by index. String getValue(int index) Returns the value of attribute by index, null if index is out of bounds. String getValue(String qName) Returns the value of attribute by name, null if name is not present. Print Page Previous Next Advertisements ”;
Parse XML Document
Java SAX Parser – Parse XML Document ”; Previous Next Java SAX(Simple API for XML) parser is an API in Java to parse XML documents. SAX parser is an event based parser and uses a Handler class to handle the events. The call back methods such as startElement(), characters(), endElement() etc., are implemented inside the Handler class to obtain the details of elements and their attributes. These call back methods are called when the parser identifies the respective events. Parse XML Using Java SAX parser Following are the steps we need to follow to parse an XML document in Java using 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: Retrieving the Elements Step 1: Implementing a Handler class Application program must implement a handler class to handle the events inside the XML document. After implementing the Handler class, it must be registered with the SAX parser. As discussed in the previous chapter, the DefaultHandler class implements ContentHandler interface. It has the methods, startDocument(), endDocument(), startElement(), endElement() and characters() functions that help us parse the XML documents. We write the code inside these methods according to our requirement. class UserHandler extends DefaultHandler { public void startDocument() { … } public void startElement(String uri, String localName, String qName, Attributes attributes) { … } public void characters(char[] ch, int start, int length) { … } public void endElement(String uri, String localName, String qName) { … } public void endDocument() { … } } Step 2: Creating a SAXParser Object The SAXParserFactory class is used to create a new factory instance which in turn is used to create the SAXParser object as follows − SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); Step 3: Reading the XML Read the XML file by specifying the proper file path as follows − File xmlFile = new File(“input.xml”); Instead of reading files, we can create an InputStream of the XML content as follows − StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“”<?xml version=”1.0″?> <rootElement></rootElement>””); ByteArrayInputStream inputStream = new ByteArrayInputStream( xmlBuilder.toString().getBytes(“UTF-8”)); Step 4: Creating object for Handler class Create an object for the already implemented UserHandler class in first step as follows − UserHandler userHandler = new UserHandler(); Step 5: Parsing the XML Document The SAXParser class has the parse() method that takes two arguments, one is the file and the other is the DefaultHandler object. This function parses the given file as XML document using the functions implemented inside the DefaultHandler class. saxParser.parse(xmlFile, userHandler); The SAXParser class also has the function parse() that takes the content as InputStream − saxParser.parse(inputStream, userHandler); Step 6: Retrieving the Elements After following the above five steps, we can now easily retrieve the required information about the elements. We should write the required code inside the methods of our Handler class in first step. All the methods available inside the ContentHandler interface are discussed in the previous chapter and in this chapter, we will implement these methods to retrieve the basic information about elements such as element name, text content and attributes. Retrieving Element Name Element name can be obtained from the startElement() method of ContentHandler interface. The third argument of this method is the name of the Element and it is of String type. We can implement this method in our Handler class and get the name of an Element. Example In the following example, we have taken XML content in the form of a String using StringBuilder class and converted into bytes using ByteArrayInputStream. In the UserHandler class, we have implemented the startElement() method and printed the name of the Element. Since, we have only single element in the XML content, that becomes the root element of the document. import java.io.ByteArrayInputStream; 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{ public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println(“Root element is “+qName); } } public class RetrieveElementName { public static void main(String args[]) { try { //Creating a SAXParser Object SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(“<college>XYZ College</college>”); ByteArrayInputStream input = new ByteArrayInputStream(xmlBuilder.toString().getBytes(“UTF-8″)); //Creating UserHandler object UserHandler userhandler = new UserHandler(); //Parsing the XML Document saxParser.parse(input, userhandler); } catch (Exception e) { e.printStackTrace(); } } } Root Element name, ”college” is printed on the output screen. Root element is college Retrieving TextContent To retrieve text content of an element, we have characters() method in ContentHandler interface. There is character array, start and length arguments in this method. As soon as the parser sees the content after “>” symbol, this method is called. The start argument carries the index of the first character after “>” symbol and length has the number of characters before it encounters “<” symbol. Example The following college.xml file has a single sub element, “department” with text content “Computer Science”. Let us write a Java program to retrieve this text content along with element names using SAX API. <college> <department>Computer Science</department> </college> The UserHandler class inherits DefaultHandler and we have implemented startElement(), endElement() and characters() method. When the parser sees the text content inside department element, this method is called and we are printing it on the console. 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 { public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println(“Start Element : ” + qName); } public void endElement(String uri, String localName, String qName) { System.out.println(“End Element : ” + qName); } public void characters(char[] ch, int start, int length) throws SAXException{ System.out.println(“Text Content : ” + new String(ch, start, length)); } } public class RetrieveTextContent { public static void main(String args[]) { try { //Creating a SAXParser Object SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); //Reading the XML File xmlFile
Modify XML Document
Java DOM Parser – Modify XML Document ”; Previous Next Java DOM parser API provides methods to modify the already existing XML documents. We can add or remove elements and attributes, modify the text content of elements and attribute values using the methods of Java DOM parser. The setTextContent() method replaces the original text of elements, removeAttribute() removes the existing attributes and the setAttribute() method sets the new attributes to elements. Modify XML Using Java DOM Parser We can modify an 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: Updating the content of XML document Step 5: Writing the content into XML file Step 6: Output to console for testing Refer this page of this section for first three steps. Step4: Updating the content of XML document We can update text content, attribute values, add new elements and new attributes to our existing XML documents. Element element = xmldoc.getDocumentElement(); element.setTextContent(“14”); element.removeAttribute(“attr_name”); element.setAttribute(“attr_name”,”attr_value”); The setTextContent(“text_content”) method is used to set the text content of an Element. This method is used with the Element object and takes String as an argument. The removeAttribute(“attr_name”) method removes the attribute from the Element object. It throws NO_MODIFICATION_ALLOWED_ERR error if the Element from which we want to remove the attribute is readonly. The setAttribute(“attr_name”,”attr_value”) method takes attribute name and attribute value as arguments and sets it to the Element object. Updating Text Content Let us consider college.xml file where we have three department details. Now, we will try to update staff count for Electrical and Electronics department from 23 to 14. The method setTextContent(“text”) is used to update the text content of an element. college.xml Following is the college.xml file before updating. Now let us try to update this in our java program. <?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> ModifyXMLDemo.java In the following java program, we retrieved all the nodes with tag name, “department” into a NodeList. Then, we iterated all the nodes to find “Electrical and Electronics” department and changed the staffCount attribute to 14. import java.io.File; import java.io.FileOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; 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 org.w3c.dom.NodeList; public class ModifyXMLDemo { public static void main(String argv[]) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); //Reading the XML file File inputFile = new File(“src/modifydom.xml”); //Parsing the XML Document Document doc = docBuilder.parse(inputFile); //Updating the staffCount for “Electrical and Electronics” department NodeList deptList=doc.getElementsByTagName(“department”); for(int i=0;i<deptList.getLength();i++) { Element element= (Element) (deptList.item(i)); String s=element.getElementsByTagName(“name”).item(0).getTextContent(); if(s.equals(“Electrical and Electronics”)) { Element staffCount = (Element) element.getElementsByTagName(“staffCount”).item(0); staffCount.setTextContent(“14”); } } //Writing the updated content into the file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); FileOutputStream output = new FileOutputStream(“college.xml”); StreamResult result = new StreamResult(output); transformer.transform(source, result); //writing the content on console StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } 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 Now, let us go a bit further and try to add one more department named “Civil” to our above “college.xml” file. To add new elements, we can use createElement(“Element_name”) method to create and appendChild(Element) to append the element to the existing document”s root element. ModifyXMLAddElementsDemo.java In the following program, we first got the root element by using getDocumentElement() method. Then, we created “Civil” department element and added to the root element. import java.io.File; import java.io.FileOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; 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; public class ModifyXMLAddElementsDemo { public static void main(String argv[]) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); //Reading the XML file File inputFile = new File(“college.xml”); //Parsing the XML Document Document doc = docBuilder.parse(inputFile); //Adding new department element Element rootElement = doc.getDocumentElement(); Element department = doc.createElement(“department”); department.setAttribute(“id”, “104”); Element name = doc.createElement(“name”); Element staffCount = doc.createElement(“staffCount”); department.appendChild(name); department.appendChild(staffCount); name.appendChild(doc.createTextNode(“Civil”)); staffCount.appendChild(doc.createTextNode(“10”)); rootElement.appendChild(department); //Creating transformer object TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); //Writing updated content into the file DOMSource source = new DOMSource(doc); FileOutputStream output = new FileOutputStream(“college.xml”); StreamResult result = new StreamResult(output); transformer.transform(source, result); //writing the content on console StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace();} } } Output The updated file after adding “Civil” department is as follows : <?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> <department id=”104″><name>Civil</name><staffCount>10</staffCount></department></college> Print Page Previous Next Advertisements ”;
Java XML Overview
Java XML Overview ”; Previous Next Java XML is simply working with an XML document from a Java program. Imagine, we have a file “products.xml” where we have product details such as name, brand and price. Now, we want to update prices for some products using Java programming. Before writing such java programs to access XML documents, we should know basics of XML. What is XML? XML stands for EXtensible Markup Language. It is a text-based markup language which is used to store and transport data. It is self-descriptive and both human-readable and, machine-readable. Following are some notable points on XML − XML is a markup language. XML is a tag based language like HTML. XML tags are not predefined like HTML. You can define your own tags which is why it is called extensible language. XML tags are designed to be self-descriptive. XML is W3C Recommendation for data storage and data transfer. XML Document An XML document is the collection of elements that define data in a well structured and organized manner. An XML document has two sections, namely, document prolog and document elements. Syntax Following is the syntax of an XML document − <?xml ?> <root_element> <element></element> … </root_element> Where, <?xml ?> is the XML declaration statement. If included, it must be kept in the first line. <root_element> is the root element and it is the parent of all other elements. <element> is the sub element of the root element. Example Following example shows Employee details with <Employee> as the root element and <name>, <role>, <salary> as sub elements. Data for each element is enclosed between opening and closing tags. <?xml version=”1.0″ ?> <Employee> <name>Kiran</name> <role>developer</role> <salary>25,000</salary> </Employee> Elements in XML An element is the building block of an XML document. It consists of an opening tag, content and a closing tag. In an xml document, there should always be a root element, inside which we can write many sub elements. Elements can also have any number of attributes inside them. Syntax Following is the syntax of an XML element − <root> <child> <subchild>…..</subchild> </child> </root> Where, <root> is the root element of the XML document. <child> is the child element and its parent is the root element. <subchild> is the sub child and its parent is the child element. Example Let us see an example where DOB(date of birth) is further structured into date, month and year. Here, <DOB> is the root element and <date>, <month>, <year> are child elements. <DOB> <date>27</date> <month>March</month> <year>2000</year> </DOB> Tags in XML Tags in XML are self-explanatory and user defined. These are enclosed in less than (<) and greater than (>) symbols. XML is case sensitive and hence opening and closing tags should have same name. Example In the following example, we have written an address element with opening and closing tags. <address>Hyderabad</address> Now, let us see some incorrect ways of writing XML tags: <Address></address> <ADDRESS></address> Since, XML is case sensitive unlike HTML, it throws the error: Opening and ending tag mismatch. Attributes in XML Elements in XML can have attributes. Attributes are name-value pairs that provide further specific information about a particular element. An element can have any number of attributes. Syntax Following is the syntax for XML attributes − <element_name attribute_name=”value” >content</element_name> Where, element_name is the name of the element. attribute_name is the name of the attribute. value is the value of the corresponding attribute. Example Now, let”s look at the following example where we have four attributes, name, class, marks and DOB for the ”Student” element. <Student name=”Kiran” class=”8″ marks=”50″ DOB=”27-03-2000″></Student> Using sub elements to replace attributes Instead of attributes, sub elements can also be used in elements to achieve the same purpose as of attributes. The same student example can also be written as follows: <Student> <name>Kiran</name> <class>8</class> <marks>50</marks> <DOB>27-03-2000</DOB> </Student> It is always a best practice to use sub elements instead of attributes. Because, sub elements can further be extended whereas attributes cannot be extended. In the above example, If we further want the date of birth as date, month and year then it can be done by using sub elements for DOB element as follows : <Student> <name>Kiran</name> <class>8</class> <marks>50</marks> <DOB> <date>27</date> <month>03</month> <year>2000</year> </DOB> </Student> XML Declaration XML declaration describes the basic format information such as version, encoding and standalone status about the entire XML document. If an XML declaration is included in the document, it must be written in the first line. By default, if declaration is not mentioned, XML parser considers the document is in version 1.0 Syntax Following is the syntax of XML declaration − <?xml version=”version_number” encoding=”encoding_type” standalone=”standalone_status” ?> Where, XML declaration starts with the character sequence <?xml and ends with the character sequence ?> version is the version number of the XML used encoding is the character encoding used for the content of XML document standalone is a boolean attribute whose default value is set to ”no”. This tells whether the XML document is standalone or uses information from external source to parse the document such as DTD(Document Type Definition). The default value is set to ”no”. Example Following example uses XML 1.0 version with encoding type UTF-16 and it is standalone. <?xml version=”1.0″ encoding=”UTF-16″ standalone=”yes” ?> XML Comments Comments in XML are used to explain the document”s purpose and details. It is always a best practice to include comments in the document
Java XML Home
Java XML Tutorial Table of content Java XML Tutorial Why to Learn Java XML? Java XML Applications Who Should Learn Java XML Prerequisites to Learn Java XML Frequently Asked Questions about Java XML PDF Version Quick Guide Resources Job Search Discussion Java XML Tutorial XML (EXtensible Markup Language) is a very popular simple text-based language that can be used as a mode of communication between different applications. It is considered as a standard means to transport and store data. JAVA provides excellent support and a rich set of libraries to parse, modify or inquire XML documents. This tutorial will teach you basic XML concepts and the usage of various types of Java based XML parsers in a simple and intuitive way. Why to Learn Java XML? Data is often uploaded and downloaded on a daily basis. Most of the data is represented in XML format. Many business applications are built in Java. There are use cases where we need to add details to our existing data, update already existing data, create new data files and query the documents. So, We should know how to access XML documents to perform these operations in Java applications. Java XML Applications Java has different libraries to parse XML documents, and XML, being an easy-to-learn and understandable language, finds its applications in many areas. Following are the various applications of Java XML − To create layouts in android mobile applications. To store data related to orders, invoices, delivery details, and so on in e-Commerce websites. To implement security features such as encryption, authentication, authorization etc. To store and transfer data in different formats across applications. To make smooth data transfer among systems in distributed computing. Who Should Learn Java XML? This tutorial has been prepared for beginners to help them understand the basic-to-advanced concepts related to XML parsing using Java Programming language. After completing this tutorial, you will find yourself at a moderate level of expertise in XML parsing using Java from where you can take yourself to higher levels of expertise. Java developers should learn Java XML as Java frameworks such as Spring, Hibernate use tools based on XML configuration. Also people who work with web services such as SOAP should know about Java XML. Also, Integration specialists use Java XML to integrate data from different systems. Prerequisites to Learn Java XML You should have knowledge on basic java programming to understand the programs covered in this tutorial. Having prior knowledge about XML will help you understand things quickly. Yet, it is not a big issue if you don”t know anything about XML because we have a chapter named “Java XML overview” that covers all the basics of XML that are required for this tutorial. Frequently Asked Questions about Java XML There are some very Frequently Asked Questions(FAQ) about Java XML, this section tries to answer them briefly. What is Java XML used for? Java XML is used to parse, create, query, and modify XML files using java libraries. What is the best library to parse XML in Java? There are many libraries to parse XML documents, though all don”t have same capabilities, it is up to you to choose the one that best suits your requirements. How to manipulate XML file in Java? XML files can be manipulated in java using Java XML libraries. How to create XML in Java? You can create XML document in Java using XML libraries such as dom, jdom, dom4j, StAX and XPath. What is the difference between Java and XML? Java is a programming language while XML is a markup language used for data storage and transport. Why we use pom XML in Java? We use pom.xml file in building maven projects. It contains all the detailed information about the project such as groupId, artifactId, version etc. How to send xml request in Java? You can create request in XML format and send the request using HttpURLConnect object. What is the structure of XML in Java? XML structure remains the same irrespective of programming language. Why do you need XML? We need XML to store and transport data in a structured format. How to Read and Write XML Files in Java? You can import related Java XML libraries and use the interfaces and methods available to read and write XML files. How to generate Java code from XML? Java code can be generated from XML using JAXB, JAXP or XML Beans/JiBX. Print Page Previous Next Advertisements ”;
Java DOM Parser
Java DOM Parser – Overview ”; Previous Next Java DOM parser is an API (Application Programming Interface) that has classes, interfaces and methods to parse XML documents by creating DOM tree structure. The Document Object Model (DOM) is an official recommendation of the World Wide Web Consortium (W3C). It defines an interface that enables programs to access and update the style, structure, and contents of XML documents. When to use Java DOM Parser? You should use a DOM parser when − You need to know a lot about the structure of a document. You need to move parts of an XML document around (you might want to sort certain elements, for example). You need to use the information in an XML document more than once. What is the result of Parsing? When you parse an XML document with a DOM parser, you will get a tree structure that contains all of the elements of your document. The DOM provides a variety of functions you can use to examine the contents and structure of the document. Advantages Following are some advantages of Java DOM parser − DOM is a very simple API to use. Easy to access and modify any part of the document since entire document is loaded into memory. Java code written for one DOM-compliant parser should run on any other DOM-compliant parser without having to do any modifications. Disadvantages Following are some of the disadvantages of Java DOM parser − Consumes more memory Not suitable for large documents. Not applicable for small devices like PDAs and cellular phones. DOM Interfaces Here are the most commonly used DOM interfaces − Interface Description Document Represents the XML or HTML document. Node primary data type of the Document Object Model (DOM) NodeList an ordered collection of nodes. Element represents an element in XML document. Attr represents an attribute of an Element object. Text represents textual content of an element or attribute, inherited from ”CharacterData” interface. DOM Methods Here are the most commonly used DOM methods − Method Description Document.getDocumentElement() returns the root element of the document. Document.getElementsByTagName() returns a NodeList of all elements within the given tag name. Node.getFirstChild() returns the first child of a given Node. Node.getLastChild() returns the last child of a given Node. Node.getNextSibling() returns the root element of the document. Node.getPreviousSibling() returns the root element of the document. Node.getAttribute(attrName) returns the attribute with the requested name for a given node. Node.getNodeName() returns the name of the node. Node.getTextContent() returns the text content of the current node and its descendants. NodeList.getLength() returns the number of nodes in the NodeList. NodeList.item(int index) returns the indexth node from the NodeList. Print Page Previous Next Advertisements ”;