Saturday, December 1, 2007

XML to String Object

How to convert a XML file to string ?
How to conver the XML Node to String format ?.

Oh, my XML parser implementation does not have directly to convert as a String. toString() method just returns object information what to do?.

Yes, in this moment, we have to write a our own logic to convert the Node as a String object. Sun Microsystems javax.xml package serves transforming the XML document to String irrespective of the XML parser Implementation(refer JSR 5 and JSR 173 and etc.,)

Even upto individual Node level transformation is possible.

  • XML Document to String
  • XML element to String
  • XML Node to String

Import following package classses apart from your application class import and org.w3c.* package.


import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

Write following method and conver simply your Node as String


public static String xmlToString(Node node) {
try {
Source source = new DOMSource(node);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}

Using Oracle implementation, we can do this XMLDocument to String by giving single command.

((XMLDocument)doc).print(System.out); 
//any of the output stream , enjoy :)

3 comments:

Anonymous said...

Nice one - that little sniplet was exactly what I was looking for!

Anonymous said...

Thanks, this accomplished what I've been looking into for hours!

Anonymous said...

Thank you! I just wanted to pass a string instead of nodes. Well done.

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com