Sometimes while programming in java, we get String
which is actually an XML and to process it, we need to convert it to XML Document (org.w3c.dom.Document
). Also for debugging purpose or to send to some other function, we might need to convert Document object to String. Here I am providing two utility functions.
Document convertStringToDocument(String xmlStr)
: This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.String convertDocumentToString(Document doc)
: This method will take input as Document and convert it to String. We will use Transformer
, StringWriter
and StreamResult
for this purpose.package com.journaldev.xml;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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.xml.sax.InputSource;
public class StringToDocumentToString {
public static void main(String[] args) {
final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
"<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
"<role>Developer</role><gen>Male</gen></Emp>";
Document doc = convertStringToDocument(xmlStr);
String str = convertDocumentToString(doc);
System.out.println(str);
}
private static String convertDocumentToString(Document doc) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
// below code to remove XML declaration
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) );
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
When we run above program, we get the same String output that we used to create DOM Document.
<?xml version="1.0" encoding="UTF-8"?><Emp id="1"><name>Pankaj</name><age>25</age>
<role>Developer</role><gen>Male</gen></Emp>
You can use replaceAll("\n|\r", "")
to remove new line characters from String and get it in compact format.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Is there any way to handle the converion for large document, as while convesion toString getting out of memory error.
- Ankit
Can you provide me a example for “Document convertStringToDocument(String xmlStr)” I am currently working on one of the project where I need to convert string to xml format
- Akshay A
Works great for me, thanks!
- Carlos Barrantes
Thanks a lot for sharing this. :).
- Nik
Why is this article still up and why is the author not responding to so many people saying it doesn’t work. The code does not work.
- Raj Ashtaputre
why the doc value is null then how we can get our xml data
- Mahadev
Hi all, i am also getting same error on parsing…Null pointer exception gets genearted…Any help is highly appreciaed
- Mehul Kishor Fatnani
Where is the replaceAll() method supposed to be used? I was thinking it should be placed on the string str before printing it out, like so: String str = convertDocumentToString(doc); str.replaceAll(“\n|\r”, “”); System.out.println(str); But the output doesn’t change…
- nekonutchi
The variable doc allways return null
- mmonikm
successfully executed but did not found useful. I want convert doc file into xml
- ahmad