How to I output org.w3c.dom.Element to string format in java?

JavaXmlDom

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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();

Solution 2 - Java

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);

Solution 3 - Java

Try jcabi-xml with one liner:

String xml = new XMLDocument(element).toString();

Solution 4 - Java

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/

Solution 5 - Java

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);
    }
}

Solution 6 - Java

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!

Solution 7 - Java

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)));
		}
	}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoView Question on Stackoverflow
Solution 1 - JavaMcDowellView Answer on Stackoverflow
Solution 2 - JavaTarsem SinghView Answer on Stackoverflow
Solution 3 - Javayegor256View Answer on Stackoverflow
Solution 4 - JavaKarlView Answer on Stackoverflow
Solution 5 - JavawierobView Answer on Stackoverflow
Solution 6 - JavathunderhawkView Answer on Stackoverflow
Solution 7 - Javavtd-xml-authorView Answer on Stackoverflow