在Java中将XML DOM打印为字符串时将前缀传播到子元素
我正在用java创建一个带有DOM api的XML,如下所示在Java中将XML DOM打印为字符串时将前缀传播到子元素,java,xml,dom,xml-namespaces,Java,Xml,Dom,Xml Namespaces,我正在用java创建一个带有DOM api的XML,如下所示 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element root = document.createElement("root"); do
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement("root");
document.appendChild(root);
Element one = document.createElementNS("http://ns1", "one");
root.appendChild(one);
one.setPrefix("ns1");
Element two = document.createElementNS("http://ns1", "two");
one.appendChild(two);
当使用以下代码打印上述DOM时,将在所有元素上生成名称空间声明(在本例中是在元素1和元素2上)。如何确保命名空间声明的前缀是继承的,并且转换器不会在每个元素上重新声明它们-
代码:
电流输出::
<root>
<ns1:one xmlns:ns1="http://ns1">
<two xmlns="http://ns1">
</two>
</ns1:one>
</root>
预期输出::
<root>
<ns1:one xmlns:ns1="http://ns1">
<ns1:two>
</ns1:two>
</ns1:one>
</root>
在createElementNS()
中的第二个属性是一个限定名(QName)。因此,如果不为元素名称指定前缀,则元素将不固定,并且名称空间将作为默认名称空间添加
而不是(你写的)
明确指定元素“2”所需的前缀
或者从父元素中提取前缀,而不是对其进行硬编码
Element two = document.createElementNS("http://ns1", one.getPrefix() + ":" + "two");
请注意,如果未指定前缀,则Node.getPrefix()
将返回null
。当然,将前缀存储在字符串变量中会使事情变得更简单
注:这些代码示例未经测试,因此不能保证结果正确,但我认为它应该是这样工作的。我知道这是旧的,但这正是我缺少的细节,所以谢谢!
Element two = document.createElementNS("http://ns1", "two");
Element two = document.createElementNS("http://ns1", "ns1:two");
Element two = document.createElementNS("http://ns1", one.getPrefix() + ":" + "two");