Create xml dom java example

Create XML File in Java using DOM parser example

In this tutorial we are going to see how to create XML File in Java using DOM parser. The basic idea is very simple. You construct the DOM object with the tree structure you want in the memory, and then you use a Transformer and a StreamResult in order to write the DOM object to a stream, in our case a File. In short the basic steps one has to take in order to create an XML File withe a DOM Parser are:

  • Create a DocumentBuilder instance.
  • Create a Document from the above DocumentBuilder .
  • Create the elements you want using the Element class and its appendChild method.
  • Create a new Transformer instance and a new DOMSource instance.
  • Create a new StreamResult to the output stream you want to use.
  • Use transform method to write the DOM object to the output stream you want.

Let’s take a closer look at the code snippet that follows:

package com.javacodegeeks.java.core; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; public class CreateXMLFileJava < public static final String xmlFilePath = "C:\\Users\\nikos7\\Desktop\\files\\xmlfile.xml"; public static void main(String argv[]) < try < DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); // root element Element root = document.createElement("company"); document.appendChild(root); // employee element Element employee = document.createElement("employee"); root.appendChild(employee); // set an attribute to staff element Attr attr = document.createAttribute("id"); attr.setValue("10"); employee.setAttributeNode(attr); //you can also use staff.setAttribute("id", "1") for this // firstname element Element firstName = document.createElement("firstname"); firstName.appendChild(document.createTextNode("James")); employee.appendChild(firstName); // lastname element Element lastname = document.createElement("lastname"); lastname.appendChild(document.createTextNode("Harley")); employee.appendChild(lastname); // email element Element email = document.createElement("email"); email.appendChild(document.createTextNode("james@example.org")); employee.appendChild(email); // department elements Element department = document.createElement("department"); department.appendChild(document.createTextNode("Human Resources")); employee.appendChild(department); // create the xml file //transform the DOM Object to an XML File TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource domSource = new DOMSource(document); StreamResult streamResult = new StreamResult(new File(xmlFilePath)); // If you use // StreamResult result = new StreamResult(System.out); // the output will be pushed to the standard output . // You can use that for debugging transformer.transform(domSource, streamResult); System.out.println("Done creating XML File"); >catch (ParserConfigurationException pce) < pce.printStackTrace(); >catch (TransformerException tfe) < tfe.printStackTrace(); >> >
   James Harley james@example.org Human Resources  

This was an example on how to create XML File in Java using DOM parser.

Читайте также:  Html control text width

Источник

Java Guides

In this article, we will learn how to create an XML file in Java using DOM XML Parser. The DOM provides many handy classes to create an XML file easily. Firstly, you have to create a Document with DocumentBuilder class, define all the XML content – node, attribute with Element class. In last, use the Transformer class to output the entire XML content to stream output, typically a File.

Development Process Steps

1. The users.xml Output File

xml version="1.0" encoding="UTF-8" standalone="no"?> Users> User id="1"> firstName>RameshfirstName> lastName>FadatarelastName> age>28age> gender>Malegender> User> User id="2"> firstName>JohnfirstName> lastName>CenalastName> age>45age> gender>Malegender> User> User id="3"> firstName>TomfirstName> lastName>CruiselastName> age>40age> gender>Malegender> User> Users>

2. Java DOM Parser to create an XML file in Java

package net.javaguides.javaxmlparser.dom; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; 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.Node; public class CreateXMLFileInJava < public static void main(String[] args) < DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try < dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // add elements to Document Element rootElement = doc.createElement("Users"); // append root element to document doc.appendChild(rootElement); // append first child element to root element rootElement.appendChild(createUserElement(doc, "1", "Ramesh", "Fadatare", "28", "Male")); // append second child rootElement.appendChild(createUserElement(doc, "2", "John", "Cena", "45", "Male")); // append third child rootElement.appendChild(createUserElement(doc, "3", "Tom", "Cruise", "40", "Male")); // for output to file, console TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); // for pretty print transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); // write to console or file StreamResult console = new StreamResult(System.out); StreamResult file = new StreamResult(new File("create_users.xml")); // write data transformer.transform(source, console); transformer.transform(source, file); > catch (Exception e) < e.printStackTrace(); > > private static Node createUserElement(Document doc, String id, String firstName, String lastName, String age, String gender) < Element user = doc.createElement("User"); // set id attribute user.setAttribute("id", id); // create firstName element user.appendChild(createUserElements(doc, user, "firstName", firstName)); // create lastName element user.appendChild(createUserElements(doc, user, "lastName", lastName)); // create age element user.appendChild(createUserElements(doc, user, "age", age)); // create gender element user.appendChild(createUserElements(doc, user, "gender", gender)); return user; > // utility method to create text node private static Node createUserElements(Document doc, Element element, String name, String value) < Element node = doc.createElement(name); node.appendChild(doc.createTextNode(value)); return node; > >
   Ramesh Fadatare 28 Male  John Cena 45 Male  Tom Cruise 40 Male   

Note that for debugging, you can change the StreamResult to output the XML content to your console.

StreamResult console = new StreamResult(System.out); StreamResult file = new StreamResult(new File("create_users.xml")); transformer.transform(source, console); // to console transformer.transform(source, file); // to file

Источник

Оцените статью