Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Document to String?

Tags:

java

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?

like image 433
Nate Avatar asked Apr 02 '10 15:04

Nate


People also ask

How do I make an XML file into a string?

XmlDocument version of XmlDocument (used in UWP apps for example), you can use yourXmlDocument. GetXml() to get the XML as a string.

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.

How do I read an XML string in Java?

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.

What is a string in 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).


1 Answers

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);     } } 
like image 169
Bozho Avatar answered Oct 21 '22 07:10

Bozho