Java DOM Tutorial
Java DOM Tutorial
Java DOM Tutorial
In this section, you will learn to count the element in XML document using DOM APIs defined in the org.apache.xerces.parsers.DOMParser package.
Wide Web
Consortium (W3C). The W3C site provides a comprehensive reference of the XML DOM. 1. Creating Blank DOM Document
This section shows you how to create the blank DOM document.
6. XML Well-Formed-ness
In this section, you will learn to check the well-formed-ness of a XML using the DOM interface. A well-formed XML document must follow the xml syntax rules.
13. Getting Dom Tree Elements and their Corresponding XML Fragments
In this section, you will learn to get the elements of a DOM tree and their corresponding XMLfragments. Each element of dom tree has a node level starting with '0'. Here the DOM tree elements and their corresponding XML fragments are displayed on the console.
This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents.
This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents. With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class. The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it is used to a DOM parser. Example is as follows:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(myInputSource); //The parse function is used to parse existing xml document.
DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling: System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory"); The instance of the class DocumentBuilder is used to create a blank document. The newDocument()method of the class returns a blank DOM document. Document doc = parser.newDocument(); Here is the full code of CreateBlankDocument.java import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class CreateBlankDocument { public static void main(String[] args) { System.out.println("Creating Balnk Document..."); try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder parser = factory.newDocumentBuilder();
//Create blank DOM Document Document doc = parser.newDocument(); }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println("Done..."); System.out.println("Exiting..."); } }
In the next section I will show you how to add root and child elements to the blank document. Saving the DOM tree to the disk file is also discussed in the next section.
This lesson shows you how to create root and child elements in the DOM tree.
<?xml version="1.0" encoding="UTF-8" ?> <root> <!-- This is comment--> <Child attribute1="The value of Attribute 1" /> </root>
Creating the root element In the previous lesson you learned how to create DocumentBuilder object and the create a blank DOM document. The following code creates a blank document.
//Create blank DOM Document Document doc = docBuilder.newDocument(); The createElement function is used to create the root element and appendChild method is used to append the element to the DOM document. //create the root element Element root = doc.createElement("root"); //all it to the xml tree doc.appendChild(root); Adding Comment Element to DOM Tree The doc.createComment function is used to create Comment object. //create a comment Comment comment = doc.createComment("This is comment"); //add in the root element root.appendChild(comment); Adding Child Element to DOM Tree The doc.createElement function is used to create Child element. //create child element Element childElement = doc.createElement("Child"); //Add the atribute to the child childElement.setAttribute("attribute1","The value of Attribute 1"); root.appendChild(childElement); Printing the DOM Tree on console An finally we will print the DOM tree on the console with the following code: TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer(); Source src = new DOMSource(doc);
Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); Here is the full code of CreateDomXml.java import org.w3c.dom.*; import import import import javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamResult;
class CreateDomXml { public static void main(String[] args) { try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Create blank DOM Document Document doc = docBuilder.newDocument(); //create the root element Element root = doc.createElement("root"); //all it to the xml tree doc.appendChild(root); //create a comment Comment comment = doc.createComment("This is comment"); //add in the root element root.appendChild(comment); //create child element Element childElement = doc.createElement("Child"); //Add the atribute to the child childElement.setAttribute("attribute1","The value of Attribute 1"); root.appendChild(childElement); TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer(); Source src = new DOMSource(doc); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); }catch(Exception e){ System.out.println(e.getMessage()); }
After reading this section, you will be able to retrieve a root element from the XML document.
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee>
<Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_E-mail> </Employee> </Employee-Detail>
Here is the Java File: GetRootNode.java import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; public class GetRootNode{ public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter xml file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = fact.newDocumentBuilder(); Document doc = builder.parse(str); Node node = doc.getDocumentElement(); String root = node.getNodeName(); System.out.println("Root Node: " + root); } else{ System.out.println("File not found!"); } } catch(Exception e){} } }
C:\vinod\xml>javac
GetRootNode.java C:\vinod\xml>java GetRootNode Enter xml file name: Employee-Detail.xml Root Node: EmployeeDetail
In this section, you will learn to count the elements present in a XML file using DOM APIs.
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email>
</Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: DOMCountElement.java import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; public class DOMCountElement{ public static void main(String[] args) { try { BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter File name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Create the builder and parse the file Document doc = factory.newDocumentBuilder().parse(xmlFile); System.out.print("Enter element name: "); String element = bf.readLine(); NodeList nodes = doc.getElementsByTagName(element); System.out.println("xml Document Contains " + nodes.getLength() + " elements."); } else{ System.out.print("File not found!"); } }
C:\vinod\xml>javac DOMCountElement.java C:\vinod\xml>java DOMCountElement Enter File name: Employee-Detail.xml Enter element name: Emp_Name xml Document Contains 3 elements.
In this section, you will learn to count the element in XML document using DOM APIs defined in the org.apache.xerces.parsers.DOMParser package.
given XML document. It asks the element name and counts its occurence in the xml file. If the given element doesn't exist it displays the '0' element. Here is the XML File: Employee-Detail.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: CountNodes.java import org.w3c.dom.*; import org.apache.xerces.parsers.DOMParser; import java.io.*; public class CountNodes{ public static void main(String[] args) { try{
BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DOMParser parser = new DOMParser(); parser.parse(str); Document doc = parser.getDocument(); System.out.print("Enter element that have to count: "); String ele = bf.readLine(); NodeList list = doc.getElementsByTagName(ele); System.out.println("Number of nodes: " + list.getLength()); } else{ System.out.println("File not found!"); } } catch (Exception e){ e.getMessage(); } }
C:\vinod\xml>javac CountNodes.java C:\vinod\xml>java CountNodes Enter file name: Employee-Detail.xml Enter element that have to count: Emp_Name Number of nodes: 3
XML Well-Formed-ness
Posted on: June 4, 2007 at 12:00 AM
In this section, you will learn to check the well-formed-ness of a XML using the DOM interface.
XML Well-Formed-ness
In this section, you will learn to check the well-formed-ness of a XML using the DOM interface. A well-formed XML document must follow the xml syntax rules. Description of program: For checking the "well-formedness" of a XML document you should use the given example. The DOMparser parsers (parse()) the XML document using the DocumentBuilder andDocumentBuilderFactory. Whenever the XML document is wellformed, it shows a message "Employee-Detail.xml is well-formed". Otherwise it displays "Employee-Detail.xml isn't well-formed.". Here is the XML File: Employee-Detail.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email>
</Employee> </Employee-Detail>
Here is the Java File: DOMParserCheck.java import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; org.xml.sax.*;
public class DOMParserCheck { static public void main(String[] arg){ try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter File name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if(file.exists()){ try { // Create a new factory to create parsers DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); // Use the factory to create a parser (builder) and use // it to parse the document. DocumentBuilder builder = dBF.newDocumentBuilder(); // builder.setErrorHandler(new MyErrorHandler()); InputSource is = new InputSource(xmlFile); Document doc = builder.parse(is); System.out.println(xmlFile + " is well-formed!"); } catch (Exception e) { System.out.println(xmlFile + " isn't well-formed!"); System.exit(1); } } else{ System.out.print("File not found!"); } } catch(IOException io){ io.printStackTrace(); } } }
C:\vinod\xml>javac DOMParserCheck.java
In this you will learn to search an element in the specified XML document using DOM APIs defined in the org.apache.xerces.parsers.DOMParser package.
<Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: SearchElement.java import org.w3c.dom.*; import org.apache.xerces.parsers.DOMParser; import java.io.*; public class SearchElement{ public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DOMParser parser = new DOMParser(); parser.parse(str); Document doc = parser.getDocument(); System.out.print("Enter element that have to count: "); String ele = bf.readLine(); NodeList list = doc.getElementsByTagName(ele); if(list.getLength() == 0){ System.out.println("Element doesn't exist in the " +
str + " Document."); } else{ System.out.println("Element occurrs " + list.getLength() + " times in the " + str); } } else{ System.out.println("File not found!"); } } catch (Exception e){ e.getMessage(); } } }
C:\vinod\xml>javac SearchElement.java C:\vinod\xml>java SearchElement Enter file name: EmployeeDetail.xml Enter element that have to count: Emp_name Element doesn't exist in the Employee-Detail.xml Document. C:\vinod\xml>java SearchElement Enter file name: EmployeeDetail.xml Enter element that have to count: Emp_Name Element occurrs 3 times in the Employee-Detail.xml
In this section, you will learn to create a XML document using the DOM APIs.
In this section, you will learn to create aXML document using the DOM APIs. This XML document uses 1.0 version and UTF-8 encoding. Description of program: This program helps in creating a XML document on the console. This program asks for the number of elements to be added in the generated xml file. It takes the root name at the console and passes it in the createElement() method. It creates the Element object and invokes the Document object . Depending upon the given number, it creates that much elements and fills them with data,. Finally, it displays the generated XML file with its version and encoding. Here is Java File: CreatXMLFile.java import import import import import import java.io.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.*; javax.xml.transform.stream.*; org.w3c.dom.*;
public class CreatXMLFile { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter number to add elements in your XML file: "); String str = bf.readLine(); int no = Integer.parseInt(str); System.out.print("Enter root: "); String root = bf.readLine(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElement(root); document.appendChild(rootElement); for (int i = 1; i <= no; i++){ System.out.print("Enter the element: "); String element = bf.readLine(); System.out.print("Enter the data: "); String data = bf.readLine(); Element em = document.createElement(element); em.appendChild(document.createTextNode(data)); rootElement.appendChild(em); } TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } }
C:\vinod\xml>javac CreatXMLFile.java C:\vinod\xml>java CreatXMLFile Enter number to add elements in your XML file: 3 Enter root: RonseIndia Enter the element: Emp-Name Enter the data: Vinod Enter the element: Emp-Code Enter the data: E-001 Enter the element: Emp-Desi Enter the data: JuniorProgrammer <?xml version="1.0" encoding="UTF-8" standalone="no"?><RonseIndia> <Emp-Name>Vino d</Emp-Name><Emp-Code>E001</Emp-Code> <Emp-Desi>JuniorProgrammer</Emp-Desi></Ro nseIndia>
In this section, you will learn to get the elements and its value using DOM APIs.
In this section, you will learn to get the elements and its value using DOM APIs. Description of program: This example parses a xml file and regenerates it at the console using the DOM APIs. This program takes a XML file and initially checks its availability . If file exists then it creates DocumentBuilderFactory. This object creates a DocumentBuilder which parses the XML document using the parse() method. It invokes the DocumentBuilder object and creates a Documentobject. Through this object you create DOM tree nodes by using the getDocumentElement() method and passes it to the DOMSource(). The DOMSource constructor creates a new input source with aDOM node. And the destination source (where you recieve the result) uses the StreamResult()constructor. Here the "System.out" shows the result on the console. Here is the XML File: Employee-Detail.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_E-
public class GetElementsDOM{ static public void main(String[] arg)throws Exception{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter XML File Name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if(file.exists()){ try { // Create a factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Use document builder factory DocumentBuilder builder = factory.newDocumentBuilder(); //Parse the document Document doc = builder.parse(xmlFile); TransformerFactory tranFact = TransformerFactory.newInstance(); Transformer transfor = tranFact.newTransformer(); Node node =doc.getDocumentElement(); Source src = new DOMSource(node); Result dest = new StreamResult(System.out); transfor.transform(src, dest); } catch (Exception e) { System.err.println(e); } } else{ System.out.print("File not found!"); } } }
C:\vinod\xml>javac GetElementsDOM.java C:\vinod\xml>java GetElementsDOM Enter XML File Name: EmployeeDetail.xml <?xml version="1.0" encoding="UTF-8"?><EmployeeDetail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@gmail.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@hotmail.com </Emp_Email> </Employee> </Employee-Detail>
In this section, you will learn to check and locate (line and column number) an error in your XML document using the DOM APIs.
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee </Employee-Detail>
Here is the Java File: DOMLocateError.java import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; org.xml.sax.*;
try { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter File name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if(file.exists()){ // Create a new factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Use the factory to create builder document. DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile);
C:\vinod\xml>javac DOMLocateError.java C:\vinod\xml>java DOMLocateError Enter File name: Employee-Detail1.xml [Fatal Error] Employee-Detail1.xml:9:1: The end-tag for element type "Employee" must end with a '>' delimiter. type: The end-tag for element type "Employee" must end with a '>' delimiter.
Line 9 Column 1
In this section, you will learn to retrieve all elements of the XML file using the DOM APIs.
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee>
<Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is Java File: DOMElements.java import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; org.xml.sax.*;
public class DOMElements{ static public void main(String[] arg){ try { BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter XML File name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if(file.exists()){ // Create a factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Use the factory to create a builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); // Get a list of all elements in the document NodeList list = doc.getElementsByTagName("*"); System.out.println("XML Elements: "); for (int i=0; i<list.getLength(); i++) { // Get element Element element = (Element)list.item(i); System.out.println(element.getNodeName()); }
C:\vinod\xml>javac DOMElements.java C:\vinod\xml>java DOMElements Enter XML File name: Employee-Detail.xml XML Elements: Employee-Detail Employee Emp_Id Emp_Name Emp_E-mail Employee Emp_Id Emp_Name Emp_E-mail Employee Emp_Id Emp_Name Emp_E-mail
In this section, you will learn to add a DOCTYPE to your XML file using the DOM APIs.
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name>
public class AddDocType{ static public void main(String[] args){ try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter XML file name: "); String xmlFile = bf.readLine(); System.out.println(); File file = new File(xmlFile); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); // Create transformer Transformer tFormer = TransformerFactory.newInstance().newTransformer(); // Set system id tFormer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, "systmId"); Source source = new DOMSource(doc); Result result = new StreamResult(System.out); tFormer.transform(source, result); System.out.println(); } else{ System.out.println("File not found!"); } } catch (Exception e){ e.getMessage(); } }
C:\vinod\xml>java AddDocType Enter XML file name: Employee-Detail.xml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE Employee-Detail PUBLIC "publicId" "systmId"> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Sushil </Emp_Name> <Emp_E-mail>Sushil@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit@yahoo.com </Emp_E-mail> </Employee> </Employee-Detail>
In this section, you will learn to get the elements of a DOM tree and their corresponding XML fragments. Each element of dom tree has a node level starting with 0.
In this section, you will learn to get the elements of a DOM tree and their corresponding XML fragments. Each element of dom tree has a node level starting with '0'. Here the DOM tree elements and their corresponding XML fragments are displayed on the console. Description of the program: This program helps you to retrieve the elements of a DOM tree and their corresponding XML fragments on the console. To parse the xml file you need the DocumentBuilder and DoucnemtBuilderFactory. With the help of this you create a NodeList through the getElementByTagName() method. The NodeList helps you in getting the length and Element. For getting the node name you use thegetNodeName() method. The transform() method displays the data source and the given destination. This program uses the "System.out" to display the data on the console. Here is the XML File: Employee-Detail2.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: DisplayElementNodes.java import import import import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamResult;
public class DisplayElementNodes { static public void main(String[] arg){ try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter a XML file name: "); String xmlFile = bf.readLine();
File file = new File(xmlFile); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer(); // Get nodes list of all elements NodeList list = doc.getElementsByTagName("*"); for (int i=0; i<list.getLength(); i++){ // Get element Element element = (Element)list.item(i); Source src = new DOMSource(element); System.out.println("Node no: " + i + " is " + element.getNodeName()); System.out.println( "Its corresponding xml representation:"); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); System.out.println("\n"); } } else{ System.out.println(xmlFile + " (file name) doesn't found!"); } } catch (Exception e){ e.getMessage(); } } }
C:\vinod\xml>javac DisplayElementNodes.java C:\vinod\xml>java DisplayElementNodes Enter a XML file name: Employee-Detail2.xml Node no: 0 is Employee-Detail Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><EmployeeDetail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee>
</Employee-Detail> Node no: 1 is Employee Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee> Node no: 2 is Emp_Id Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Emp_Id> E-001 </Emp_Id> Node no: 3 is Emp_Name Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Emp_Name> Vinod </Emp_Name> Node no: 4 is Emp_E-mail Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail>
In this section, you will learn to create a clone of a element in the DOM tree. In general, the cloning means to create a duplicate.
The following program helps you in creating a clone of any element of the specified XML file. For creating a DOM object , you need the DocumentBuilderFactoty and the DocumentBuilder objects. After parsing it displays a xml file on the console using the transform() method. At run time the program asks for a element name to clone . Here the element1.cloneNode(true) method creates a clone and element1.getParentNode().insertBefore(copyElement, element1.getNextSibling())inserts the clone element at the specified position. Here is the XML File: Employee-Detail2.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: DOMCloneElements.java import import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamResult;
public class DOMCloneElements { static public void main(String[] arg){ try { BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter XML file name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer tformer = tFactory.newTransformer();
Source source = new DOMSource(doc); Result result = new StreamResult(System.out); System.out.println(xmlFile + " file: "); tformer.transform(source, result); System.out.println(); System.out.print("Enter the element to clone: "); String clone = bf.readLine(); System.out.print("Enter data to add: "); String addElement = bf.readLine(); //////////////////////////////// NodeList list = doc.getElementsByTagName(clone); Element element1 = (Element)list.item(0); Element copyElement = (Element) element1.cloneNode(true); element1.getParentNode().insertBefore(copyElement, element1.getNextSibling()); element1.appendChild(doc.createTextNode(addElement)); tformer.transform(source, result); } else{ System.out.println("File not found!"); } } catch (Exception e){ e.getMessage(); } }
C:\vinod\xml>javac DOMCloneElements.java C:\vinod\xml>java DOMCloneElements Enter XML file name: Employee-Detail2.xml Employee-Detail2.xml file: <?xml version="1.0" encoding="UTF-8" standalone="no"? ><Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee> </Employee-Detail> Enter the element to clone: Emp_Id Enter data to add: E011 <?xml version="1.0" encoding="UTF-8" standalone="no"? ><Employee-Detail> <Employee>
<Emp_Id> E-001 E011</Emp_Id><Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee> </Employee-Detail>
In this section, you will learn to remove any element from a given XML document. Whenever you remove the xml element from the xml document the data are also lost from the xml element.
<?xml version="1.0"?> <E-mail> <To>Rohan</To> <From>Amit</From> <Subject>Surprise....</Subject> <Body>Be ready for a cruise...</Body> </E-mail>
Here is the Java File: RemoveElement.java
public class RemoveElement { static public void main(String[] arg) { try{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a XML file name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); System.out.print("Enter an element which have to delete: "); String remElement = bf.readLine(); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer tFormer = tFactory.newTransformer(); Element element = (Element)doc.getElementsByTagName(remElement).item(0); // Remove the node element.getParentNode().removeChild(element); // Normalize the DOM tree to combine all adjacent nodes doc.normalize(); Source source = new DOMSource(doc); Result dest = new StreamResult(System.out); tFormer.transform(source, dest); System.out.println(); } else{ System.out.println("File not found!"); } } catch (Exception e){ System.err.println(e); System.exit(0); } } }
Enter an element which have to delete: Subject <?xml version="1.0" encoding="UTF8" standalone="no"?><E-mail> <To>Rohan</To> <From>Amit</From> <Body>Be ready for a cruise...</Body> </E-mail>
In this section, you will learn to retrieve the data from a XML file. All xml files store the data. You can add and modify the data in the xml document using the DOM APIs.
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Sushil </Emp_Name> <Emp_Email>Sushil@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: GetData.java import import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamResult;
public class GetData{ static public void main(String[] arg) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter XML file name: ");
String xmlFile = bf.readLine(); File file = new File(xmlFile); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); // Create transformer Transformer tFormer = TransformerFactory.newInstance().newTransformer(); // Output text type tFormer.setOutputProperty(OutputKeys.METHOD, "text"); // Write the document to a file Source source = new DOMSource(doc); Result result = new StreamResult(System.out); tFormer.transform(source, result); } else{ System.out.println("File not found!"); } } catch (Exception e){ System.err.println(e); System.exit(0); } } }
C:\vinod\xml>javac GetData.java C:\vinod\xml>java GetData Enter XML file name: Employee-Detail.xml E-001 Vinod Vinod1@yahoo.com E-002 Sushil Sushil@yahoo.com E-003 Amit
Amit@yahoo.com
In this section, you will learn to store data (retrieved from the XML document) to a specified file (with extension '.txt', '.doc', '.xls', '.shtml' etc.) in different formats (text, xml, html etc.).
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Sushil </Emp_Name> <Emp_Email>Sushil@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: StoreData.java import import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamResult;
public class StoreData{ static public void main(String[] arg) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter XML file name: ");
String xmlFile = bf.readLine(); File file = new File(xmlFile); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); // Create transformer Transformer tFormer = TransformerFactory.newInstance().newTransformer(); // Output Types (text/xml/html) tFormer.setOutputProperty(OutputKeys.METHOD, "text"); // Write the document to a file Source source = new DOMSource(doc); Result result = new StreamResult(new File("vk.txt")); tFormer.transform(source, result); System.out.println("File creation successfully!"); } else{ System.out.println("File not found!"); } } catch (Exception e){ System.err.println(e); System.exit(0); } } }
C:\vinod\xml>javac StoreData.java C:\vinod\xml>java StoreData Enter XML file name: Employee-Detail.xml File creation successfully! C:\vinod\xml>
In this section, you will learn to validate a xml file against a DTD (Document Type Definition) using the DOM APIs. A DTD defines the document structure with a list of legal elements and attributes.
<?xml version = "1.0" ?> <!DOCTYPE Employee SYSTEM "Employee.dtd"> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </Employee>
Here is the DTD File: Employee.dtd
Emp_Name, Emp_E-mail)> <!ELEMENT Emp_Id (#PCDATA)> <!ELEMENT Emp_Name (#PCDATA)> <!ELEMENT Emp_E-mail (#PCDATA)>
Here is the Java file: DOMValidateDTD.java import import import import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.validation.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamSource; javax.xml.transform.stream.StreamResult;
public class DOMValidateDTD { public static void main(String args[]) { try{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new org.xml.sax.ErrorHandler() { //Ignore the fatal errors public void fatalError(SAXParseException exception) throws SAXException { } //Validation errors public void error(SAXParseException e) throws SAXParseException { System.out.println("Error at " +e.getLineNumber() + " line."); System.out.println(e.getMessage()); System.exit(0); } //Show warnings public void warning(SAXParseException err) throws SAXParseException{ System.out.println(err.getMessage()); System.exit(0); } }); Document xmlDocument = builder.parse( new FileInputStream("Employeexy.xml")); DOMSource source = new DOMSource(xmlDocument); StreamResult result = new StreamResult(System.out); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, "Employee.dtd"); transformer.transform(source, result); }
C:\vinod\xml>javac DOMValidateDTD.java C:\vinod\xml>java DOMValidateDTD <?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE Employee SYSTEM "Employee.dtd"> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee>
In this example we have provided you a simple java example with the source code that will make it possible to access the XML file through Java.
File MyFile.xml
<?xml version="1.0"?> <student> <student-name> <firstname>Anusmita</firstname> <lastname>Singh</lastname> </student-name> <student-address> <address>Rohini</address> <city>Delhi</city> </student-address> </student>
Here is the code of AccessingXmlFile.java import import import import java.io.File; javax.xml.parsers.DocumentBuilder; javax.xml.parsers.DocumentBuilderFactory; org.w3c.dom.*;
public class AccessingXmlFile { public static void main(String argv[]) { try { File file = new File("C:\\MyFile.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(file); document.getDocumentElement().normalize(); System.out.println("Root element "+ document.getDocumentElement().getNodeName()); NodeList node = document.getElementsByTagName("student"); System.out.println("Information of the students"); for (int i = 0; i < node.getLength(); i++) { Node firstNode = node.item(i); if (firstNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) firstNode;
NodeList firstNameElemntList = element.getElementsByTagName("firstname"); Element firstNameElement = (Element) firstNameElemntList.item(0); NodeList firstName = firstNameElement.getChildNodes(); System.out.println("First Name:"+ ((Node)firstName.item(0).getNodeValue()); NodeList lastNameElementList = element.getElementsByTagName("lastname"); Element lastNameElement = (Element) lastNameElementList.item(0); NodeList lastName = lastNameElement.getChildNodes(); System.out.println("Last Name :"+ ((Node)lastName.item(0).getNodeValue()); NodeList addressList = element.getElementsByTagName("address"); Element addressElement = (Element) addressList.item(0); NodeList address = addressElement.getChildNodes(); System.out.println("Address : " + ((Node) address.item(0)).getNodeValue()); NodeList cityList = element.getElementsByTagName("city"); Element cityElement = (Element) cityList.item(0); NodeList city = cityElement.getChildNodes(); System.out.println("City : " + ((Node) city.item(0)).getNodeValue()); } } } catch (Exception e) { e.printStackTrace(); }
} }
In the above example, the method DocumentBuilderFactory.newInstance() enables applications to obtain a parser that produces DOM. The DocumentBuilder provides the DOM document instances from XML document. The Document refers to the HTML or XML document. The getDocumentElement()method provides the XML root Element. The getElementsByTag Name() provides the tag. Then get the value of node by getNodeValue(). Following output will be displayed on the console: