默认的空XML命名空间xmlns=""属性会被添加吗?

6

我有一段简单的代码,其中我创建了根元素并将子元素附加到它上面。问题在于子元素带有空的xmlns=""属性,尽管我不希望它出现。这只是第一个子元素的问题,而第二层嵌套的子元素已经正常了。

因此,以下是代码 -

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

将会输出结果 -
<?xml version="1.0" encoding="UTF-8"?>
<metamodel xmlns="http://someNamespace.ru">
   <groups xmlns="">
      <group/>
   </groups>
</metamodel>

改为 -

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

注意,正如我上面所说的,标签<group>已经不再受xmlns的限制。
1个回答

5
您想要的标记显示了默认命名空间中的所有元素。为了实现这一点,您必须在默认命名空间中创建所有元素。
实际输出结果中出现了,因为groups及其group子元素是在无命名空间中创建的。
Element groupsEl = doc.createElement("groups");

将此更改为

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

同样,改变

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

为了

Element groupEl = doc.createElementNS("http://someNamespace.ru","group");

谢谢您,医生,这很有帮助 :) 不过,对我来说似乎有点奇怪,因为它可以被继承,但每次都必须明确设置。 - Dmitry Bakhtiarov
你的想法很容易理解,特别是在XML中,子元素默认会继承层次结构中更高级别元素上做出的命名空间声明。然而,这是一种词法作用域;将其视为创建更为合适,而且创建调用需要提供命名空间,否则它将默认为无命名空间。 - kjhughes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接