- How to create XML programmatically in java / How to create XML using DOM parser in java / How to create XML file from java program
- How to write XML file in Java – (DOM Parser)
- 1. Write XML to a file
- 2. Pretty Print XML
- 3. Write XML elements, attributes, comments CDATA, etc
- 4. DOM FAQs
- 4.1 How to disable the XML declaration?
- 4.2 How to change the XML encoding?
- 4.3 How to pretty-print the XML?
- 4.4 How to hide the XML declaration `standalone=”no”`?
- 4.5 How to change the XML declaration version?
- Create XML File in Java using DOM parser example
- How to create XML file in Java
- 1- Create XML using Transformer
- 2- Output
- 3- Source Code
- Summary
- Next Steps
How to create XML programmatically in java / How to create XML using DOM parser in java / How to create XML file from java program
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
XML stands for eXtended Markup Language and is a widely used standard for transmitting information across systems mainly due to the flexibility it provides in creating the structure and data it can contain. That is, application developers can create their own structure which suits their application as there are no pre-defined tags in XML. Scenario Since it is a widely used standard, there arises a vital requirement to create an XML document either in the form of a String or a physical file from java application. Practical scenario is when data of one component of your application data is stored in a database table and you want to make it available to some other application or for some other component of your application which is separate from this component and you cannot share the database details with either of them. The solution is you create an XML out of table data and share it with any component.
Create XML from Java Program using DOM Parser Given below is a sample XML structure which we will be creating from java program. The structure is simple but enough for learning purpose and you can create more complex structure if you know how things work.
The XML has a root tag with name Users and has child tags for each user details. A user tag is named as User which has user name in a child tag. Each user tag also has an id attribute. Code to create above XML is given below followed by a detailed explanation of the same.
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; 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; public static void main(String[] args) throws ParserConfigurationException, TransformerException { DocumentBuilder builder = null; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw e; } Document document = builder.newDocument(); // create root element Element root = document.createElement("Users"); // attach it to the document document.appendChild(root); // create user node Element user = document.createElement("User"); // create its id attribute user.setAttribute("id", "2"); // add user node to root node root.appendChild(user); // create name node and set its value Element userName = document.createElement("name"); userName.setTextContent("codippa"); // attach this node to user node user.appendChild(userName); // write xml Transformer transformer; try { TransformerFactory transformerFactory = TransformerFactory .newInstance(); transformer = transformerFactory.newTransformer(); Result output = new StreamResult(new File("codippa.xml")); Source input = new DOMSource(document); // if you want xml to be properly formatted transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(input, output); } catch (TransformerConfigurationException e) { throw e; } catch (TransformerException e) { throw e; } }
Details :
At first step, create a org.w3c.Document object. This object is a handle to the XML file. Next we need to create individual nodes as required by the XML structure. In every XML, the first node is the root node which contains all other nodes. Hence, we first create a root node. A node is created using createElement() method of org.w3c.Document . Method of creating a node is the same, whether it is a root node or a child node. The only difference what makes a node as root or child is the node to which we attach the newly created node.
For Example, we get a node using createElement() method. Let’s name it as node1. Now if we attach it to the document object, then it becomes the root node. If we attach it to another node, say node2, then node1 becomes the child of node2. For creating an attribute of a node (such as id attribute in ), call setAtrribute() method on a node. This method takes two arguments, attribute name and its value. A node is attached using appendChild() method. For creating multiple nodes inside a node, such as , nodes inside node, create three nodes, one of User and the other two of name and country. Attach name and country nodes to the User node (using appendChild() method off course) and attach User node to the root node.
In this way multiple nodes can be created and attached to the root or to another node (for creating child nodes).
- Besides using setAttribute() method directly on a node, an attribute can also be created using below code
// create an attribute with given name Attr attr = document.createAttribute("id"); // set its value attr.setValue("1"); // attach it to desired node user.setAttributeNode(attr);
// this will write to a file Result output = new StreamResult(new File("codippa.xml")); // this will print to console Result output = new StreamResult(System.out);
Did this post help you solve a problem? Wonderful . Keep visiting for more solutions…
How to write XML file in Java – (DOM Parser)
This tutorial shows how to use the Java built-in DOM APIs to write data to an XML file.
1. Write XML to a file
Steps to create and write XML to a file.
- Create a Document doc .
- Create XML elements, attributes, etc., and append to the Document doc .
- Create a Transformer to write the Document doc to an OutputStream .
package com.mkyong.xml.dom; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.OutputStream; public class WriteXmlDom1 < public static void main(String[] args) throws ParserConfigurationException, TransformerException < DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); doc.createElement("staff"); rootElement.appendChild(doc.createElement("staff")); //. create XML elements, and others. // write dom document to a file try (FileOutputStream output = new FileOutputStream("c:\\test\\staff-dom.xml")) < writeXml(doc, output); >catch (IOException e) < e.printStackTrace(); >> // write doc to output stream private static void writeXml(Document doc, OutputStream output) throws TransformerException < TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(output); transformer.transform(source, result); >>
2. Pretty Print XML
2.1 By default, the Transformer outputs the XML in a compact format.
2.2 We can set the OutputKeys.INDENT in Transformer to enable the pretty print format.
TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); // pretty print XML transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(output); transformer.transform(source, result);
3. Write XML elements, attributes, comments CDATA, etc
The below example uses a DOM parser to create and write XML to an OutputStream .
package com.mkyong.xml.dom; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class WriteXmlDom3 < public static void main(String[] args) throws ParserConfigurationException, TransformerException < DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); // staff 1001 // add xml elements Element staff = doc.createElement("staff"); // add staff to root rootElement.appendChild(staff); // add xml attribute staff.setAttribute("id", "1001"); // alternative // Attr attr = doc.createAttribute("id"); // attr.setValue("1001"); // staff.setAttributeNode(attr); Element name = doc.createElement("name"); // JDK 1.4 //name.appendChild(doc.createTextNode("mkyong")); // JDK 1.5 name.setTextContent("mkyong"); staff.appendChild(name); Element role = doc.createElement("role"); role.setTextContent("support"); staff.appendChild(role); Element salary = doc.createElement("salary"); salary.setAttribute("currency", "USD"); salary.setTextContent("5000"); staff.appendChild(salary); // add xml comment Comment comment = doc.createComment( "for special characters like < &, need CDATA"); staff.appendChild(comment); Element bio = doc.createElement("bio"); // add xml CDATA CDATASection cdataSection = doc.createCDATASection("HTML tag testing
"); bio.appendChild(cdataSection); staff.appendChild(bio); // staff 1002 Element staff2 = doc.createElement("staff"); // add staff to root rootElement.appendChild(staff2); staff2.setAttribute("id", "1002"); Element name2 = doc.createElement("name"); name2.setTextContent("yflow"); staff2.appendChild(name2); Element role2 = doc.createElement("role"); role2.setTextContent("admin"); staff2.appendChild(role2); Element salary2 = doc.createElement("salary"); salary2.setAttribute("currency", "EUD"); salary2.setTextContent("8000"); staff2.appendChild(salary2); Element bio2 = doc.createElement("bio"); // add xml CDATA bio2.appendChild(doc.createCDATASection("a & b")); staff2.appendChild(bio2); // print XML to system console writeXml(doc, System.out); > // write doc to output stream private static void writeXml(Document doc, OutputStream output) throws TransformerException < TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); // pretty print transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(output); transformer.transform(source, result); >>
]]>
mkyong support 5000 testing yflow admin 8000
4. DOM FAQs
Some DOM parser commonly asked questions.
4.1 How to disable the XML declaration?
We can configure the OutputKeys.OMIT_XML_DECLARATION to disblae the XML declaration.
// hide the xml declaration // hide transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
4.2 How to change the XML encoding?
We can configure the OutputKeys.ENCODING to change the XML encoding.
// set xml encoding // transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
4.3 How to pretty-print the XML?
We can configure the OutputKeys.INDENT to enable the pretty print XML.
// pretty print transformer.setOutputProperty(OutputKeys.INDENT, "yes");
4.4 How to hide the XML declaration `standalone=”no”`?
We can configure the document.setXmlStandalone(true) to hide the XML declaration standalone=»no» .
TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); // pretty print transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // hide the standalone="no" doc.setXmlStandalone(true); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(output); transformer.transform(source, result);
4.5 How to change the XML declaration version?
We can configure the document.setXmlVersion(«version») to change the XML declaration version.
// set xml version // doc.setXmlVersion("1.1");
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.
How to create XML file in Java
In this tutorial, we show how to create a new XML file using DOM parser provided by JDK.
We’re going to create an XML called students.xml which lists students along with their basic information.
1- Create XML using Transformer
The following code snippet appends 3 student elements to a root element called students and then transforms the document object to a pretty XML file using transform() method of Transformer.
private static void createPrettyXMLUsingDOM() < try < DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // students root element Element rootElement = doc.createElement("students"); doc.appendChild(rootElement); // student elements for(int i=1; i// Write the content into XML file DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("students-new.xml")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); // Beautify the format of the resulted XML transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("indent-amount", "4"); transformer.transform(source, result); > catch(Exception ex) < ex.printStackTrace(); >>
2- Output
After executing the above code, you should get the following XML:
Hussein 1 Hussein 2 Hussein 3
3- Source Code
You can download the source code from this repository: Read-XML
Summary
In this tutorial, we show how to create a new XML file using DOM parser provided by JDK.
Next Steps
If you’re interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you’ll need to become a professional developer.
Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.