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!
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.
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.
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.
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", "");
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