- Create XML Document in Java
- Create DocumentBuilderFactory
- Create new Document
- Create XML Document Root Element
- Create Child XML Element
- Transform XML Document to String
- Create XML Document Complete Example
- Related Posts:
- Java Guides
- Development Process Steps
- 1. The users.xml Output File
- 2. Java DOM Parser to create an XML file in Java
- Create XML File in Java using DOM parser example
- Java Guides
- Development Process Steps
- 1. The output create_jdom_users.xml File
- 2. Program to create XML file in Java using JDOM Parser
Create XML Document in Java
With this short blog post I am going to share with you how to create XML document using Java.
Often we need to send HTTP Post request that contains JSON or XML payload. Earlier I have shared a blog post on different ways to create JSON Payload by converting Java objects into JSON. Below is an example of how to use DocumentBuilder from javax.xml.parsers to construct XML document from scratch.
In the example below we are going to create a very simple XML document of the below structure. Once you are able to create this simple XML document, you will be able to enhance it with new elements as needed.
Create DocumentBuilderFactory
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
Create new Document
DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument();
Create XML Document Root Element
// Create Person root element Element personRootElement = doc.createElement( "Person" ); doc.appendChild( personRootElement );
Create Child XML Element
// Create First Name Element Element firstNameElement = doc.createElement( "FirstName" ); firstNameElement.appendChild( doc.createTextNode( "Sergey" ) ); personRootElement.appendChild( firstNameElement );
and we will create a second child element right away:
// Create Last Name Element Element lastNameElement = doc.createElement( "LastName" ); lastNameElement.appendChild( doc.createTextNode( "Kargopolov" ) ); personRootElement.appendChild( lastNameElement );
Transform XML Document to String
// Transform Document to XML String TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform( new DOMSource( doc ), new StreamResult( writer ) );
and we can now get value of String, so that we can use it as we need. For example we can send it as a body of HTTP Request to our RESTful Web Services API endpoint.
// Get the String value of final xml document personXMLStringValue = writer.getBuffer().toString();
and this is it! I will paste a complete example in a single class file below.
Create XML Document Complete Example
Below is a complete example in the form of single public static void main function. You should be able to run it as is.
package com.appsdeveloperblog.xml; import java.io.StringWriter; 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.Document; import org.w3c.dom.Element; /** * * @author skargopolov */ public class PersonXMLDocument < public static void main(String[] args) < String personXMLStringValue = null; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); try < DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // Create Person root element Element personRootElement = doc.createElement("Person"); doc.appendChild(personRootElement); // Create First Name Element Element firstNameElement = doc.createElement("FirstName"); firstNameElement.appendChild(doc.createTextNode("Sergey")); personRootElement.appendChild(firstNameElement); // Create Last Name Element Element lastNameElement = doc.createElement("LastName"); lastNameElement.appendChild(doc.createTextNode("Kargopolov")); personRootElement.appendChild(lastNameElement); // Transform Document to XML String TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); // Get the String value of final xml document personXMLStringValue = writer.getBuffer().toString(); >catch (ParserConfigurationException | TransformerException e) < e.printStackTrace(); >System.out.println("personXMLStringValue = " + personXMLStringValue); > >
I hope this short and simple example of how to create xml document in Java was helpful to you!
If you have questions please comment below. Hopefully myself or other web site visitors will be able to help you out.
Also, checkout the below list of books that will help you learn how to work with XML in Java.
Related Posts:
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
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.
Java Guides
In the previous articles, we have learned How to read XML file in Java using JDOM parser and How to Update or Modify XML file in Java – JDOM Parser. In this article, we will learn how to create an XML file using JDOM parser in Java.
JDOM Document provides methods to easily create elements and attributes. XMLOutputter class can be used to write the Document to an OutputStream or Writer object.
Development Process Steps
- The output create_jdom_users.xml File
- Program to create XML file in Java using JDOM Parser.
1. The output create_jdom_users.xml File
xml version="1.0" encoding="UTF-8"?> Users> User id="1"> firstName>RameshfirstName> lastName>FadatarelastName> age>28age> gender>Malegender> User> User id="2"> firstName>TomfirstName> lastName>CruiselastName> age>45age> gender>Malegender> User> User id="3"> firstName>TonyfirstName> lastName>StarklastName> age>40age> gender>Malegender> User> User id="3"> firstName>AmirfirstName> lastName>KhanlastName> age>50age> gender>Malegender> User> Users>
2. Program to create XML file in Java using JDOM Parser
package net.javaguides.javaxmlparser.jdom; import java.io.FileWriter; import java.io.IOException; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class CreateXMLFile < public static void main(String[] args) < try < Document doc = new Document(); doc.setRootElement(new Element("Users")); doc.getRootElement().addContent(createUserXMLElement("1", "Ramesh", "Fadatare", "28", "Male")); doc.getRootElement().addContent(createUserXMLElement("2", "Tom", "Cruise", "45", "Male")); doc.getRootElement().addContent(createUserXMLElement("3", "Tony", "Stark", "40", "Male")); doc.getRootElement().addContent(createUserXMLElement("3", "Amir", "Khan", "50", "Male")); // new XMLOutputter().output(doc, System.out); XMLOutputter xmlOutput = new XMLOutputter(); // xmlOutput.output(doc, System.out); // display nice nice xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new FileWriter("create_jdom_users.xml")); System.out.println("File Saved!"); > catch (IOException io) < System.out.println(io.getMessage()); > > private static Element createUserXMLElement(String id, String firstName, String lastName, String age, String gender) < Element user = new Element("User"); user.setAttribute(new Attribute("id", id)); user.addContent(new Element("firstName").setText(firstName)); user.addContent(new Element("lastName").setText(lastName)); user.addContent(new Element("age").setText(age)); user.addContent(new Element("gender").setText(gender)); return user; > >