Convert String to XML file in Java.

Hello Friends,

In the previous example we have seen how to convert XMl to String. Now this example will do the exact opposite of the previous one i.e. convert from String to XML. We will now try to convert the String stream into an XML file object. Here is the simple code for that.

[java]

package cyb.others;

import java.io.File;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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.xml.sax.InputSource;

public class StringToXML {
public static void main(String []args)
{
String xmlToString = “”;
DocumentBuilderFactory docfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docbuilder;
try
{
docbuilder = docfactory.newDocumentBuilder();
Document stringDocument = docbuilder.parse( new InputSource(new StringReader(xmlToString)));
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer transformer = tranFactory.newTransformer();

//Uncomment this if you need to remove the line –
//< ?xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?>

//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, “yes”);

//Uncomment this is you want to remove – standalone=”no”
//stringDocument.setXmlStandalone(true);

Source source = new DOMSource(stringDocument);
Result destination = new StreamResult( new File(“newCreatedFile.xml”));
transformer.transform( source, destination );

}
catch (Exception e)
{
e.printStackTrace();
}
}
}

[/java]

Here, in the above code there are some commented data, once you uncomment it you can see the changes in the xml file. Hope this will help you.

Regards,

Nikhil Naoghare.

One thought on “Convert String to XML file in Java.”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.