我正在使用String值创建W3C Document对象.一旦我创建了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);
Run Code Online (Sandbox Code Playgroud)
我用作输入的内容:
<product>
<arg0>DDDDDD</arg0>
<arg1>DDDD</arg1>
</product>
Run Code Online (Sandbox Code Playgroud)
输出应该是什么样的:
<ns2:product xmlns:ns2="http://com">
<arg0>DDDDDD</arg0>
<arg1>DDDD</arg1>
</ns2:product>
Run Code Online (Sandbox Code Playgroud)
我还需要将前缀值和命名空间添加到输入xml字符串中.如果我尝试上面的代码,我得到这个例外:
NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助!
ale*_*xel 25
由于没有一种简单的方法来重命名根元素,我们必须用具有正确名称空间和属性的元素替换它,然后将所有原始子元素复制到其中.不需要强制命名空间声明,因为通过为元素提供正确的命名空间(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);
Run Code Online (Sandbox Code Playgroud)
在原始代码中,作者试图像这样声明一个元素名称空间:
.setAttributeNS("http://com", "xmlns:ns2", "Test");
Run Code Online (Sandbox Code Playgroud)
第一个参数是属性的名称空间,因为它是名称空间属性,所以它需要有http://www.w3.org/2000/xmlns/ URI.声明的命名空间应该进入第3个参数
.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ns2", "http://com");
Run Code Online (Sandbox Code Playgroud)