我正在使用字符串值创建一个 W3C 文档对象。创建 Document 对象后,我想将命名空间添加到该文档的根元素。这是我当前的代码:
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
document.getDocumentElement().setAttributeNS("http://com", "xmlns:ns2", "Test");
document.setPrefix("ns2");
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource(document);
Result dest = new StreamResult(new File("c:\\xmlFileName.xml"));
aTransformer.transform(src, dest);
我用什么作为输入:
<product>
<arg0>DDDDDD</arg0>
<arg1>DDDD</arg1>
</product>
输出应该是这样的:
<ns2:product xmlns:ns2="http://com">
<arg0>DDDDDD</arg0>
<arg1>DDDD</arg1>
</ns2:product>
我还需要将前缀值和命名空间添加到输入的 xml 字符串中。如果我尝试上面的代码,我会得到这个异常:
NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
感谢您的帮助!
最佳答案
由于没有一种简单的方法来重命名根元素,我们必须用具有正确命名空间和属性的元素替换它,然后将所有原始子元素复制到其中。不需要强制声明命名空间,因为通过为元素提供正确的命名空间 (URI) 并设置前缀,声明将是自动的。
用这个替换 setAttribute
和 setPrefix
(第 2,3 行)
String namespace = "http://com";
String prefix = "ns2";
// Upgrade the DOM level 1 to level 2 with the correct namespace
Element originalDocumentElement = document.getDocumentElement();
Element newDocumentElement = document.createElementNS(namespace, originalDocumentElement.getNodeName());
// Set the desired namespace and prefix
newDocumentElement.setPrefix(prefix);
// Copy all children
NodeList list = originalDocumentElement.getChildNodes();
while(list.getLength()!=0) {
newDocumentElement.appendChild(list.item(0));
}
// Replace the original element
document.replaceChild(newDocumentElement, originalDocumentElement);
在原始代码中,作者试图像这样声明一个元素命名空间:
.setAttributeNS("http://com", "xmlns:ns2", "Test");
第一个参数是属性的命名空间,因为它是一个命名空间属性,所以它需要有 http://www.w3.org/2000/xmlns/网址。声明的命名空间应该进入第3个参数
.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ns2", "http://com");
关于java - 将命名空间添加到已创建的 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11133754/