Java examples to read an XML file and print XML string to console or write XML to file.
1. Convert XML to String
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’stransform()
method.javax.xml.transform.TransformerFactory
: Factory to createTransformer
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));
2. Convert XML to String
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;
}
3. Write XML to a File
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();
}
}
3. Complete Example
The complete code used to run the example.
public class ConvertStringToXML {
public static void main(String[] args) {
final String xmlStr = "<employees>" +
" <employee id=\"101\">" +
" <name>Lokesh Gupta</name>" +
" <title>Author</title>" +
" </employee>" +
" <employee id=\"102\">" +
" <name>Brian Lara</name>" +
" <title>Cricketer</title>" +
" </employee>" +
"</employees>";
//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.
Happy Learning !!
Comments