Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant way to convert an XML Document to a String in Java than this code?

Tags:

java

xml

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;         }     } 
like image 207
Brian Avatar asked Nov 24 '08 21:11

Brian


People also ask

Can we convert XML to string in Java?

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.

How do I convert a file to string in Java?

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.

Is XML compatible with Java?

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.


2 Answers

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);    } 
like image 80
ykaganovich Avatar answered Oct 11 '22 12:10

ykaganovich


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?

like image 41
Fernando Miguélez Avatar answered Oct 11 '22 13:10

Fernando Miguélez