Here is the code currently used.
public String getStringFromDoc(org.w3c.dom.Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); writer.flush(); return writer.toString(); } catch(TransformerException ex) { ex.printStackTrace(); return null; } }
Java Code to Convert an XML Document to String For converting the XML Document to String, we will use TransformerFactory , Transformer and DOMSource classes. "</BookStore>"; //Call method to convert XML string content to XML Document object.
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.
XML provides a universal syntax for Java semantics (behavior). Simply put, this means that a developer can create descriptions for different types of data to make the data behave in various ways with Java programming code, and can later repeatedly use and modify those descriptions.
Relies on DOM Level3 Load/Save:
public String getStringFromDoc(org.w3c.dom.Document doc) { DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); return lsSerializer.writeToString(doc); }
The transformer API is the only XML-standard way to transform from a DOM object to a serialized form (String in this case). As standard I mean SUN Java XML API for XML Processing.
Other alternatives such as Xerces XMLSerializer or JDOM XMLOutputter are more direct methods (less code) but they are framework-specific.
In my opinion the way you have used is the most elegant and most portable of all. By using a standard XML Java API you can plug the XML-Parser or XML-Transformer of your choice without changing the code(the same as JDBC drivers). Is there anything more elegant than that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With