0

I have a following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<parent xmlns="urn:parent:ns:1.0"/>

I figured out how to convert XML string into element and append it to existing element using this so.

Procedure goes like this:

String text = "<child></child>";
Document document = builder.parse(new InputSource(new 
    StringReader(text)));
Element element = document.getDocumentElement();
Element importedNode = (Element) parent.importNode(element, true);
parent.getDocumentElement().appendChild(importedNode);

This produces:

<?xml version="1.0" encoding="UTF-8"?>
<parent xmlns="urn:parent:ns:1.0">
    <child xmlns=""/>
</parent>

Child element clears its default namespace, and I would like to 'inherit' the namespace from the parent (in this case urn:parent:ns:1.0).

It would be preferable if solution would use only JRE API for XML, no 3rd party libs (e.g. dom4j etc.)

igobivo
  • 433
  • 1
  • 4
  • 17
  • as a sidenote, I would not like to edit child XML text, e.g. to hardcode parent namespace inside, and then do the parsing. – igobivo Dec 07 '17 at 10:07

1 Answers1

1

This solution is inspired by this so:

String text = "<child></child>";
Document document = builder.parse(new InputSource(new 
    StringReader(text)));
Element originalElement = document.getDocumentElement();

Element newDocumentElement = 
    document.createElementNS("urn:parent:ns:1.0", 
    originalElement.getNodeName());

// no child elements, otherwise append all children to 
// newDocumentElement

Element importedNode = (Element) parent.importNode(newDocumentElement, 
    true);    
parent.getDocumentElement().appendChild(importedNode);
igobivo
  • 433
  • 1
  • 4
  • 17