I have a DOM-Document and I extract a certain node using XPath. After that I want to serialize that node to XML. I am using the following code:
TransformerFactory
.newInstance()
.newTransformer()
.transform(new DOMSource(node),
new StreamResult(getOutputStream()));
This works in a simple document, but consider the following document:
<xml xmlns:foo="...">
<bar foo:bar="xyz" />
</xml>
In this case if I want to serialize the node “bar”, then the code above breaks, because the transformer says:
Namespace for prefix ‘foo’ has not been declared
How can I get the transformer to copy the namespace definitions into the new document?
Set your
DocumentBuilderFactoryto be namespace aware.