javawaveblogs-20

Friday, October 5, 2007

Code to convert from Xml-String to Document and Document to String

package ora.in;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
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;
import org.xml.sax.SAXException;

/**
* Code to convert from Xml-String to Document and Document to String.
*
* @author Muthu
*/
public class S2DandD2S
{
public static Document loadXmlFileToDocument( String strXml,
boolean ignoreComments )
{
Document docRet = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setIgnoringComments( ignoreComments );
DocumentBuilder docBuilder = factory.newDocumentBuilder();
docRet = docBuilder.parse( new InputSource( new StringReader(
strXml ) ) );
}
catch (SAXException e)
{
System.out.println( "SAXException" );
}
catch (IOException e)
{
System.out.println( "IOException" );
}
catch (ParserConfigurationException e)
{
System.out.println( "ParserConfigurationException" );
}
catch (FactoryConfigurationError e)
{
System.out.println( "FactoryConfigurationError" );
}
return docRet;
}

/**
* @param args
*/
public static void main( String[] args )
{
try
{
String xml = "Some exception file as string";

Document document = loadXmlFileToDocument( xml, false );
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

Source srcDocument = new DOMSource( document );

// Preparing the source which is the document created above.
StringWriter writer = new StringWriter();
Result destxml = new StreamResult( writer );

// Transformingdocument to destination xml.
aTransformer.transform( srcDocument, destxml );

System.out.println( writer.toString() );
System.out.println( "Successfully transformed" );
}
catch (Exception e)
{
System.out.println( "exec " + e );
}
}
}

No comments:

diggthis