Serialize XML child and keep namespaces in Java
        Posted  
        
            by 
                Guido García
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Guido García
        
        
        
        Published on 2011-11-18T09:44:52Z
        Indexed on 
            2011/11/18
            9:51 UTC
        
        
        Read the original article
        Hit count: 452
        
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' />
© Stack Overflow or respective owner