6

I have simple code where I create root element and append child to it. The problem is that child appends with empty xmlns="" attribute, though I don't expect it. It is a problem only of the first child, and the child of second nesting level is already Ok.

So, the following code -

DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element rootEl = doc.createElementNS("http://someNamespace.ru", "metamodel");
doc.appendChild(rootEl);
Element groupsEl = doc.createElement("groups");
// This appends with xmlns=""
rootEl.appendChild(groupsEl);
Element groupEl = doc.createElement("group");
// This appends normally
groupsEl.appendChild(groupEl);

Will result to output -

<?xml version="1.0" encoding="UTF-8"?>
<metamodel xmlns="http://someNamespace.ru">
   <groups xmlns="">
      <group/>
   </groups>
</metamodel>

Instead of -

<?xml version="1.0" encoding="UTF-8"?>
<metamodel xmlns="http://someNamespace.ru">
   <groups>
      <group/>
   </groups>
</metamodel>

Note, as I said above, the tag <group> is already free from xmlns.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Dmitry Bakhtiarov
  • 373
  • 1
  • 5
  • 14

1 Answers1

5

Your desired markup shows all elements in the default namespace. In order to achieve this, you have to create all elements in the default namespace.

The actual output you're getting has <groups xmlns=""> because groups, and its group child element were created in no namespace:

Element groupsEl = doc.createElement("groups");

Change this to

Element groupsEl = doc.createElementNS("http://someNamespace.ru", "groups");

Similarly, change

Element groupEl = doc.createElement("group");

to

Element groupEl = doc.createElementNS("http://someNamespace.ru","group");
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Thank you Doc, this helped :) Though, it seems a bit strange for me, that you have to set it every time explicitly, though it could be inherited. – Dmitry Bakhtiarov Mar 19 '18 at 09:53
  • Your thinking is understandable, especially given that in XML a descendant element does, by default, inherit a namespace declaration made on an element higher in the hierarchy. However, that's a sort of lexical scoping; think of this more as creation, and the creation call wants to be given the namespace, or it defaults to no namespace. – kjhughes Mar 20 '18 at 11:43