how to convert dom4j document object to string
15,838
Solution 1
asXml() return String from Document object
String text = document.asXML()
Solution 2
Why can't you just do:
String result = dom.toXML().toString();
If you want to do it the long way, then you use a TransformerFactory to transform the DOM to anything you want. First thing you do is wrap your Document in a DOMSource
DOMSource domSource = new DOMSource(document);
Prepare a StringWriter so we can route the stream to a String:
StringWriter writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
Prepare a TransformationFactory so you can transform the DOM to the source provided:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory .newTransformer();
transformer.transform(domSource, streamResult);
Finally, you get the String:
String result = writer.toString();
Hope that helped!
Author by
Shamik
Updated on June 13, 2022Comments
-
Shamik almost 2 years
Just trying to find a way to convert a Dom4J Document content to String. It has a asXML() API which converts the content to a XML. In my case,I'm editing a non-xml DOM structure using Dom4J and trying to convert the content to String. I know its possible in case of w3c document.
Any pointers will be appreciated.
Thanks
-
javanna about 13 yearsHave you solved? Why
asXml()
doesn't work for you? I don't understand what you need, can you clarify your question please?
-
-
zaid hussian over 12 yearsHe stated he wanted non-XML, though he didn't elaborate on what the desired format actually was. Your solution produces XML.
-
Enerccio over 5 yearsmaybe because you are using SAX?