I've been fiddling with this for over twenty minutes and my Google-foo is failing me.
Let's say I have an XML Document created in Java (org.w3c.dom.Document):
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); Element rootElement = document.createElement("RootElement"); Element childElement = document.createElement("ChildElement"); childElement.appendChild(document.createTextNode("Child Text")); rootElement.appendChild(childElement); document.appendChild(rootElement); String documentConvertedToString = "?" // <---- How?
How do I convert the document object into a text string?
XmlDocument version of XmlDocument (used in UWP apps for example), you can use yourXmlDocument. GetXml() to get the XML as a string.
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.
In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.
A single string that can be referenced from the application or from other resource files (such as an XML layout). 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).
public static String toString(Document doc) { try { StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); } catch (Exception ex) { throw new RuntimeException("Error converting to String", ex); } }
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