Java provides very robust API for XML Processing. Transforming XML String to org.w3c.dom.Document and vise versa is very simple. XMLTransformations.java given below is written using JDK6. Method getDocumentAsString transforms org.w3c.dom.Document to plain String.Method getStringAsDocument transforms plain String to org.w3c.dom.Document.
XMLTransformations.java
XMLTransformations.java
import java.io.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import org.xml.sax.InputSource; /** * XMLTransformations Utilities. * @author Tejas Purohit */ public class XMLTransformations { public XMLTransformations() { } /** * Transforms given org.w3c.dom.Document to String. * @param node Node to convert to String * @return String representation of given org.w3c.dom.Document */ public String getDocumentAsString(Document doc) { String result = null; try { // Getting DOM Source DOMSource domSource = new DOMSource(doc); // Getting Output Stream to write result ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); // Getting new TransformerFactory TransformerFactory transformerfactory = TransformerFactory.newInstance(); // Getting new Transformer Transformer transformer = transformerfactory.newTransformer(); // Transforms DOMSource to StreamResult transformer.transform(domSource, new StreamResult(byteOut)); result = byteOut.toString(); // Getting String from ByteArrayOutputStream } catch (Exception ex) { ex.printStackTrace(); } return result; } /** * Builds org.w3c.dom.Document from given String. * @param strXML XML as String * @return org.w3c.dom.Document builded from String */ public Document getStringAsDocument(String strXML) { Document doc = null; try { // Getting new DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Setting namespace aware to true factory.setNamespaceAware(true); // Getting new DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // Parsing String to Document doc = builder.parse(new InputSource(new StringReader(strXML))); } catch (Exception ex) { ex.printStackTrace(); } return doc; } }
Comments
Post a Comment
Is this content helpful? Leave appreciation, feedback, suggestions, issues anything.