Below Java code parse the book.xml file.




<?xml version="1.0"?>


   <book id="bok101">

      <author>Gambardella, Matthew</author>





      <description>Sun certified Java programming reference .</description>


   <book id="bok102">

      <author>Ralls, Kim</author>

      <title>XML Reference</title>




      <description>An in-depth look at creating applications

      with XML.</description>




Java program to write xml using DOM parser





import javax.xml.parsers.*;


import javax.xml.transform.*;


import javax.xml.transform.dom.*;




import org.w3c.dom.*;


public class WriteXMLFile {


      public static void main(String[] args) throws Exception {


            BufferedReader bf = new BufferedReader(new InputStreamReader(;


            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



            DocumentBuilder documentBuilder = documentBuilderFactory



            Document document = documentBuilder.newDocument();


            Element rootElement = document.createElement(root);




            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);








            TransformerFactory transformerFactory = TransformerFactory



            Transformer transformer = transformerFactory.newTransformer();


            DOMSource source = new DOMSource(document);


            StreamResult result = new StreamResult(System.out);


            transformer.transform(source, result);






Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on ; I would like to hear from you :)