I have an org.w3c.dom.Element
object passed into my method. I need to see the whole xml string including its child nodes (the whole object graph). I am looking for a method that can convert the Element
into an xml format string that I can System.out.println
on. Just println()
on the 'Element' object won't work because toString()
won't output the xml format and won't go through its child node. Is there an easy way without writing my own method to do that? Thanks.

- 7,721
- 4
- 40
- 55
-
see also: https://stackoverflow.com/questions/1219596/how-to-i-output-org-w3c-dom-element-to-string-format-in-java – Joshua Goldberg Jun 12 '22 at 17:06
7 Answers
Assuming you want to stick with the standard API...
You could use a DOMImplementationLS:
Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
String str = serializer.writeToString(node);
If the <?xml version="1.0" encoding="UTF-16"?> declaration bothers you, you could use a transformer instead:
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node),
new StreamResult(buffer));
String str = buffer.toString();

- 107,573
- 31
- 204
- 267
-
7This is the solution if you are getting [html: null] and would expect the HTML. Added this comment so that google can index the answer hopefully. – Donal Tobin Jan 06 '10 at 15:25
-
3You can still use LSSerializer and output "UTF-8". Use LSOutput with StringWriter instead and set the encoding type to "UTF-*8" – ricosrealm Jun 29 '11 at 21:40
-
1
-
2`` declaration bothers... we can also add this line `serializer .getDomConfig().setParameter("xml-declaration", false);` in first solution.... – Tarsem Singh Oct 31 '13 at 08:32
-
thanks for your answer, that's really great. But I have a problem with it, sometimes some tags of the matched parts are removed and the text content of them is displayed solely. Do you have any suggestions for this problem? – Amin Heydari Alashti Dec 03 '18 at 07:00
-
Oneliner: `((org.w3c.dom.ls.DOMImplementationLS)element.getOwnerDocument().getImplementation()).createLSSerializer().writeToString(element)` – arve0 May 09 '19 at 13:22
-
Both approaches fail if there are namespace prefixes defined in an "outer" element. See https://stackoverflow.com/q/56872970/274677 – Marcus Junius Brutus Jul 03 '19 at 15:00
-
One problem with this approach is that it's extremely inefficient. The `createLSSerializer()` method results in the `WebappClassLoaderBase` having to reload the class every time you want to write an XML element to a string. If your application is trying to do this thousands of times per second, it's not really feasible. Is there a more efficient way to do this? – Dasmowenator Feb 18 '22 at 22:17
Simple 4 lines code to get String
without xml-declaration (<?xml version="1.0" encoding="UTF-16"?>
) from org.w3c.dom.Element
DOMImplementationLS lsImpl = (DOMImplementationLS)node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
LSSerializer serializer = lsImpl.createLSSerializer();
serializer.getDomConfig().setParameter("xml-declaration", false); //by default its true, so set it to false to get String without xml-declaration
String str = serializer.writeToString(node);

- 14,139
- 7
- 51
- 71
Try jcabi-xml with one liner:
String xml = new XMLDocument(element).toString();

- 102,010
- 123
- 446
- 597
-
New versions of jcabi-xml don't support Element as param, only Node/File/String. – Ermintar Dec 17 '19 at 10:22
Not supported in the standard JAXP API, I used the JDom library for this purpose. It has a printer function, formatter options etc. http://www.jdom.org/

- 3,170
- 1
- 21
- 28
-
+1 for it not being the intent of the standard org.w3c.dom API. If I'm interested in blocks of XML as text, I usually just try to parse it out as text with a regex match (if the search criteria is easily represented as a regex). – Cornel Masson Mar 24 '15 at 13:33
If you have the schema of the XML or can otherwise create JAXB bindings for it, you could use the JAXB Marshaller to write to System.out:
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
@XmlRootElement
public class BoundClass {
@XmlAttribute
private String test;
@XmlElement
private int x;
public BoundClass() {}
public BoundClass(String test) {
this.test = test;
}
public static void main(String[] args) throws Exception {
JAXBContext jxbc = JAXBContext.newInstance(BoundClass.class);
Marshaller marshaller = jxbc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(new JAXBElement(new QName("root"),BoundClass.class,new Main("test")),System.out);
}
}

- 4,299
- 1
- 26
- 27
this is what i s done in jcabi:
private String asString(Node node) {
StringWriter writer = new StringWriter();
try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
// @checkstyle MultipleStringLiterals (1 line)
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.VERSION, "1.0");
if (!(node instanceof Document)) {
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
}
trans.transform(new DOMSource(node), new StreamResult(writer));
} catch (final TransformerConfigurationException ex) {
throw new IllegalStateException(ex);
} catch (final TransformerException ex) {
throw new IllegalArgumentException(ex);
}
return writer.toString();
}
and it works for me!

- 11
- 1
With VTD-XML, you can pass into the cursor and make a single getElementFragment call to retrieve the segment (as denoted by its offset and length)... Below is an example
import com.ximpleware.*;
public class concatTest{
public static void main(String s1[]) throws Exception {
VTDGen vg= new VTDGen();
String s = "<users><user><firstName>some </firstName><lastName> one</lastName></user></users>";
vg.setDoc(s.getBytes());
vg.parse(false);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/users/user/firstName");
int i=ap.evalXPath();
if (i!=1){
long l= vn.getElementFragment();
System.out.println(" the segment is "+ vn.toString((int)l,(int)(l>>32)));
}
}
}

- 1
- 1

- 3,319
- 4
- 22
- 30