Empty default XML namespace xmlns=“” attribute being added?

有些话、适合烂在心里 提交于 2019-12-13 13:24:53

问题


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.


回答1:


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");


来源:https://stackoverflow.com/questions/49323227/empty-default-xml-namespace-xmlns-attribute-being-added

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!