开发者

Rename root node of XML (with namespace prefix) in Java

开发者 https://www.devze.com 2023-04-03 13:17 出处:网络
I\'m trying to use the renameNode() method of the org开发者_Python百科.w3c.dom.Document class to rename the root node of an XML document.

I'm trying to use the renameNode() method of the org开发者_Python百科.w3c.dom.Document class to rename the root node of an XML document.

My code is similar to this:

xml.renameNode(Element, "http://newnamespaceURI", "NewRootNodeName");

The code does rename the root element but doesn't apply the namespace prefix. Hard-coding the namespace prefix would not work as it has to be dynamic.

Any ideas why it is not working?

Many thanks


I tried it with 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();
}

The output is (formatting added by me):

<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>

So it works like expected. The root node has a new local name and new namespace while the child nodes remains the same including their namespaces.


I managed to sort this by looking up the namespace prefix like this:

String namespacePrefix = rootelement.lookupPrefix("http://newnamespaceURI");

and then using this with the renameNode method:

xml.renameNode(Element, "http://newnamespaceURI", namespacePrefix + ":" + "NewRootNodeName");
0

精彩评论

暂无评论...
验证码 换一张
取 消