Serialize XML child and keep namespaces in Java
- by Guido García
I have an Document object that is modeling a XML like this one:
<RootNode xmlns="http://a.com/a" xmlns:b="http://b.com/b">
<Child />
</RootNode>
Using Java DOM, I need to get the <Child> node and serialize it to XML, but keeping the root node namespaces. This is what I currently have, but it does not serialize the namespaces:
public static void main(String[] args) throws Exception {
String xml = "<RootNode xmlns='http://a.com/a' xmlns:b='http://b.com/b'><Child /></RootNode>";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
Node childNode = doc.getFirstChild().getFirstChild();
// serialize to string
StringWriter sw = new StringWriter();
DOMSource domSource = new DOMSource(childNode);
StreamResult streamResult = new StreamResult(sw);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.transform(domSource, streamResult);
String serializedXML = sw.toString();
System.out.println(serializedXML);
}
Current output:
<?xml version="1.0" encoding="UTF-8"?>
<Child/>
Expected output:
<?xml version="1.0" encoding="UTF-8"?>
<Child xmlns='http://a.com/a' xmlns:b='http://b.com/b' />