Java xpath to return an entire element as string

The solution I found was to get the org.w3c.dom.Node with xpath (DOM would work too). Then I created a javax.xml.transform.dom.DOMSource from the node and transformed that to a string with javax.xml.transform.TransformerFactory.

Node node = // the node you want to serialize
xmlOutput = new StreamResult(new StringWriter());
transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), xmlOutput);
String nodeAsAString = xmlOutput.getWriter().toString();

This is easily factored into a class for reuse. Unfortunately, the is no .OuterXml property in Java as there is in .NET. All you .NETer's can smirk now.

Tags:

Java

Xml

Xpath