I have an org.w3c.dom.Element object passed into my method. I need to see the whole xml string including its childnodes (the whole object graph). I am looking for a method that can convert the Element into 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.
A:
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/
+9
A:
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();
McDowell
2009-08-02 20:47:41
That is a good solution. Thanks
2009-08-05 15:06:44
This 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
2010-01-06 15:25:14
A:
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);
}
}
wierob
2009-08-02 20:49:18