我试图使用org.w3c.dom的renameNode()方法。类来重命名XML文档的根节点。
我的代码类似于这样:
xml.renameNode(Element, "http://newnamespaceURI", "NewRootNodeName");
代码重命名根元素,但不应用命名空间前缀。硬编码命名空间前缀是行不通的,因为它必须是动态的。
知道为什么它不工作吗?
多谢
我在JDK 6上尝试过:
public static void main(String[] args) throws Exception {
// Create an empty XML document
Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
// Create the root node with a namespace
Element root = xml.createElementNS("http://oldns", "doc-root");
xml.appendChild(root);
// Add two child nodes. One with the root namespace and one with another ns
root.appendChild(xml.createElementNS("http://oldns", "child-node-1"));
root.appendChild(xml.createElementNS("http://other-ns", "child-node-2"));
// Serialize the document
System.out.println(serializeXml(xml));
// Rename the root node
xml.renameNode(root, "http://new-ns", "new-root");
// Serialize the document
System.out.println(serializeXml(xml));
}
/*
* Helper function to serialize a XML document.
*/
private static String serializeXml(Document doc) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Source source = new DOMSource(doc.getDocumentElement());
StringWriter out = new StringWriter();
Result result = new StreamResult(out);
transformer.transform(source, result);
return out.toString();
}
输出是(格式由我添加):
<doc-root xmlns="http://oldns">
<child-node-1/>
<child-node-2 xmlns="http://other-ns"/>
</doc-root>
<new-root xmlns="http://new-ns">
<child-node-1 xmlns="http://oldns"/>
<child-node-2 xmlns="http://other-ns"/>
</new-root>
所以它像预期的那样工作。根节点有一个新的本地名称和新的名称空间,而子节点保持不变,包括它们的名称空间。
我设法通过像这样查找名称空间前缀来对其进行排序:
String namespacePrefix = rootelement.lookupPrefix("http://newnamespaceURI");
,然后使用renameNode方法:
xml.renameNode(Element, "http://newnamespaceURI", namespacePrefix + ":" + "NewRootNodeName");