Java Convert XML to String – Write XML Dom to a File
Java examples to read an XML file and print XML string to console or write XML to file.
To convert an XML object i.e org.w3c.dom.Document into a string, you need the following classes:
- javax.xml.transform.Transformer : An instance of this class can transform a source tree into a result tree, using it’s transform() method.
- javax.xml.transform.TransformerFactory : Factory to create Transformer instance.
- javax.xml.transform.dom.DOMSource : Source tree in the form of a Document Object Model (DOM) tree.
- javax.xml.transform.stream.StreamResult : An holder for a transformation result tree, which may be XML, plain Text, HTML, or some other form of markup.
For demo purposes, we are extending the example of reading an XML string to XML Dom. At a high level, we use the Transformer.transform(source, target) for the conversion.
- For writing to a string, use StringWriter instance.
- For writing to a file, use FileOutpurStream instance.
transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
In the following example, we are converting the input Document object to a String. We can then use this string to print in console or log files.
public static String convertXmlDomToString(Document xmlDocument) < TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try < transformer = tf.newTransformer(); // Uncomment if you do not require XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //A character stream that collects its output in a string buffer, //which can then be used to construct a string. StringWriter writer = new StringWriter(); //transform document to string transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer)); return writer.getBuffer().toString(); >catch (TransformerException e) < e.printStackTrace(); >catch (Exception e) < e.printStackTrace(); >return null; >
In the following example, we are using FileOutputStream to write the parsed XML content to the specified file.
private static void writeXmlDocumentToFile(Document xmlDocument, String fileName) < TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try < transformer = tf.newTransformer(); //Uncomment if you do not require XML declaration //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //Write XML to file FileOutputStream outStream = new FileOutputStream(new File(fileName)); transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream)); >catch (TransformerException e) < e.printStackTrace(); >catch (Exception e) < e.printStackTrace(); >>
The complete code used to run the example.
public class ConvertStringToXML < public static void main(String[] args) < final String xmlStr + " Lokesh Gupta" + " " + " " + " Brian Lara" + " " + " " + ""; //Use method to convert XML string content to XML Document object Document doc = convertStringToXMLDocument(xmlStr); //Convert XML to String String outputXML = convertXmlDomToString(doc); System.out.println("Output string : " + outputXML); //Write XML to File writeXmlDocumentToFile(doc, "c:/temp/test.xml"); > private static Document convertStringToXMLDocument(String xmlString) < //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try < //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document doc = builder.parse(new InputSource(new StringReader(xmlString))); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > public static String convertXmlDomToString(Document xmlDocument) < TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try < transformer = tf.newTransformer(); // Uncomment if you do not require XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //A character stream that collects its output in a string buffer, //which can then be used to construct a string. StringWriter writer = new StringWriter(); //transform document to string transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer)); return writer.getBuffer().toString(); >catch (TransformerException e) < e.printStackTrace(); >catch (Exception e) < e.printStackTrace(); >return null; > private static void writeXmlDocumentToFile(Document xmlDocument, String fileName) < TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try < transformer = tf.newTransformer(); //Uncomment if you do not require XML declaration //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //Write XML to file FileOutputStream outStream = new FileOutputStream(new File(fileName)); transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream)); >catch (TransformerException e) < e.printStackTrace(); >catch (Exception e) < e.printStackTrace(); >> >
Drop me your questions in the comments section.
Java Write XML
The Java built-in Document Object Model API is used to create and write XML files in Java. This tutorial demonstrates how to write XML to console and files in Java.
Java Write XML
As mentioned above, DOM API is used to write XML into files in Java. Here is a simple example of writing XML to a file in Java.
package Delfstack; 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.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Write_XML public static void main(String[] args) throws ParserConfigurationException, TransformerException DocumentBuilderFactory Doc_Build_Factory = DocumentBuilderFactory.newInstance(); DocumentBuilder Document_Builder = Doc_Build_Factory.newDocumentBuilder(); // the root elements for DOM Document //create XML fields, elements, etc. Document document = Document_Builder.newDocument(); Element Root_Element = document.createElement("School"); document.appendChild(Root_Element); document.createElement("Teacher"); Root_Element.appendChild(document.createElement("Teacher")); document.createElement("Student"); Root_Element.appendChild(document.createElement("Student")); // write DOM document in a file try (FileOutputStream output_file = new FileOutputStream("school.xml")) Write_Xml(document, output_file); System.out.println("The XML has been successfully written to school.xml"); > catch (IOException e) e.printStackTrace(); > > // Method to generate XML. Writing output stream private static void Write_Xml(Document document, OutputStream output_file) throws TransformerException TransformerFactory Transformer_Factory = TransformerFactory.newInstance(); Transformer New_Transformer = Transformer_Factory.newTransformer(); DOMSource Source_XML = new DOMSource(document); StreamResult Result_XML = new StreamResult(output_file); New_Transformer.transform(Source_XML, Result_XML); > >
The code above will create a file and write XML syntax to it. See output:
The XML has been successfully written to school.xml
Let’s try another example with more fields, and this example will write the XML to the file and the console both. See example:
package Delfstack; import java.io.File; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; 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 Write_XML public static void main(String[] args) DocumentBuilderFactory Doc_Builder_Factory = DocumentBuilderFactory.newInstance(); DocumentBuilder Document_Builder; try Document_Builder = Doc_Builder_Factory.newDocumentBuilder(); Document document = Document_Builder.newDocument(); //adding elements to Document Element Root_Element = document.createElementNS("https://www.delftstack.com/", "Tutorials"); document.appendChild(Root_Element); //add a first child element to the root element Root_Element.appendChild(Get_Tutorial(document, "1", "Perform String to String Array Conversion in Java", "https://www.delftstack.com/howto/java/how-to-perform-string-to-string-array-conversion-in-java/", "Java", "May-21, 2020")); //add a second child Root_Element.appendChild(Get_Tutorial(document, "2", "Compile a C++ Program Using GCC", "https://www.delftstack.com/howto/cpp/gcc-compile-cpp/", "C++", "March-25, 2022")); //add third child Root_Element.appendChild(Get_Tutorial(document, "3", "Python Tutorial - Introduction", "https://www.delftstack.com/tutorial/python-3-basic-tutorial/python-introduction/", "Python", "January-29, 2018")); //create output TransformerFactory Transformer_Factory = TransformerFactory.newInstance(); Transformer transformer = Transformer_Factory.newTransformer(); //open indent for the xml code transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource Dom_Source = new DOMSource(document); //write to file and console both StreamResult XML_file = new StreamResult(new File("delftstack.xml")); StreamResult XML_console = new StreamResult(System.out); //write data transformer.transform(Dom_Source, XML_file); transformer.transform(Dom_Source, XML_console); System.out.println("The XML Has been written to the file and console"); > catch (Exception e) e.printStackTrace(); > > private static Node Get_Tutorial(Document document, String id, String article_name, String link, String programming_language, String date_created) Element tutorial = document.createElement("Tutorial"); //set the tutorial id attribute tutorial.setAttribute("Id", id); //create article name element tutorial.appendChild(Get_Tutorial_Elements(document, tutorial, "ArticleName", article_name)); //create the Link element tutorial.appendChild(Get_Tutorial_Elements(document, tutorial, "Link", link)); //create the Programming Language element tutorial.appendChild(Get_Tutorial_Elements(document, tutorial, "ProgrammingLanguage", programming_language)); //create Date Created element tutorial.appendChild(Get_Tutorial_Elements(document, tutorial, "DateCreated", date_created)); return tutorial; > //method to create text node private static Node Get_Tutorial_Elements(Document document, Element element, String element_name, String element_value) Element element_node = document.createElement(element_name); element_node.appendChild(document.createTextNode(element_value)); return element_node; > >
The above code will create an XML file for the tutorials of delftstack.com . Each tutorial consists of four fields, ArticleName , Link , ProgrammingLanguage , and DateCreated .
The code will create the XML file and also write the XML to the console. See outputs:
Perform String to String Array Conversion in Java https://www.delftstack.com/howto/java/how-to-perform-string-to-string-array-conversion-in-java/ Java May-21, 2020 Compile a C++ Program Using GCC https://www.delftstack.com/howto/cpp/gcc-compile-cpp/ C++ March-25, 2022 Python Tutorial - Introduction https://www.delftstack.com/tutorial/python-3-basic-tutorial/python-introduction/ Python January-29, 2018 The XML Has been written to the file and console
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.