[英]Rename root node of XML (with namespace prefix) in Java
我正在尝试使用org.w3c.dom.Document类的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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.