Benson Cheng wrote:
> Is there anybody know what's the best way to rename a node?  

Which API are you using? If you are writing a SAX or XNI
filter, then it's easy. However, I'm guessing that you're
using the DOM. In that case, there is no way to rename an
element or attribute. People often complain about this
but the DOM is meant to be extensible so that a specific
document factory may return customized object nodes for
specific element types. And in this situation, it doesn't
make sense to allow nodes to be renamed.

In short, you'll have to create a new node, move the old
children into the new node and then replace the old node
with the new one. For example:

  Document doc = /* ... */;
  Element root = doc.getDocumentElement();
  Element newRoot = doc.createElement("HLI");
  NamedNodeMap attrs = root.getAttributes();
  int attrCount = attrs.getLength();
  for (int i = 0; i < attrCount; i++) {
    // I always get the first attribute because I'm
    // moving it over to the new element.
    Attr attr = (Attr)attrs.item(0);
    newRoot.setAttributeNode(attr);
  }
  Node child = root.getFirstElement();
  while (child != null) {
    // The appendChild call will automatically remove
    // the node from its old parent
    newRoot.appendChild(child);
    // After the removal of the node, it won't have its
    // old siblings, so the "next" node is just the first
    // child again.
    child = root.getFirstChild();
  }
  doc.replaceChild(newRoot, root);

Disclaimer: I'm doing this from memory. So if I made a
mistake, just check the DOM API.

-- 
Andy Clark * [EMAIL PROTECTED]

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to