how to convert dom4j document object to string
Asked Answered
C

3

9

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

Chastain answered 7/4, 2011 at 1:48 Comment(1)
Have you solved? Why asXml() doesn't work for you? I don't understand what you need, can you clarify your question please?Terrill
S
12

asXml() return String from Document object

String text = document.asXML()
Soll answered 22/7, 2016 at 10:26 Comment(0)
D
3

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!

Deron answered 7/4, 2011 at 2:34 Comment(1)
He stated he wanted non-XML, though he didn't elaborate on what the desired format actually was. Your solution produces XML.Mckenna
M
0

How can you have a non XML dom,

a Dom is in essence an XML document,

asXml() returns a string representation of the Dom , which is XML,

if you need to pull just the text values then you can iterate through the dom and getValue() on elements but what you are asking for seems to be the xml string,

Maurinemaurise answered 25/11, 2011 at 11:41 Comment(1)
maybe because you are using SAX?Casiecasilda

© 2022 - 2024 — McMap. All rights reserved.