空的默认XML名称空间xmlns =“”属性被添加? [英] Empty default XML namespace xmlns="" attribute being added?

查看:198
本文介绍了空的默认XML名称空间xmlns =“”属性被添加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的代码,可以在其中创建根元素并将子元素附加到该元素。问题是子级追加了空的 xmlns = 属性,尽管我不希望这样。仅第一个孩子有问题,而第二个嵌套级别的孩子已经可以。

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.

因此,以下代码-

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 中免费了。

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

推荐答案

您所需的标记将显示默认名称空间中的所有元素。为了实现这一点,必须在默认名称空间中创建所有元素。

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.

所获得的实际输出具有< groups xmlns => ,因为 groups 及其 group 子元素是在no中创建的名称空间:

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

将其更改为

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

类似地,更改

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

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

这篇关于空的默认XML名称空间xmlns =“”属性被添加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆