Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Document to String

What's the simplest way to get the String representation of a XML Document (org.w3c.dom.Document)? That is all nodes will be on a single line.

As an example, from

<root>   <a>trge</a>   <b>156</b> </root> 

(this is only a tree representation, in my code it's a org.w3c.dom.Document object, so I can't treat it as a String)

to

"<root> <a>trge</a> <b>156</b> </root>" 

Thanks!

like image 647
bluish Avatar asked Mar 28 '11 08:03

bluish


People also ask

How do I make an XML file into a string?

StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); xmlDoc. WriteTo(xmlTextWriter); return stringWriter. ToString(); The problem with this method is that if I have " ((quotes) which I have in attributes) it escapes them.

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.

What is a string in XML?

Note: A string is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). So, you can combine string resources with other simple resources in the one XML file, under one <resources> element. file location: res/values/filename.xml.


1 Answers

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String output = writer.getBuffer().toString().replaceAll("\n|\r", ""); 
like image 93
WhiteFang34 Avatar answered Sep 27 '22 21:09

WhiteFang34