The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > org.w3c.dom  [30 examples] > Elements  [3 examples]

e533. Changing the Name of a DOM Element

There is no method to change the name of an element. The only way to change the name is to create another element with the new name, copy the attributes, copy the children, and finally replace the node.
    // Obtain a document; this method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", false);
    
    // Obtain the root element
    Element element = doc.getDocumentElement();
    
    // Create an element with the new name
    Element element2 = doc.createElement("newname");
    
    // Copy the attributes to the new element
    NamedNodeMap attrs = element.getAttributes();
    for (int i=0; i<attrs.getLength(); i++) {
        Attr attr2 = (Attr)doc.importNode(attrs.item(i), true);
        element2.getAttributes().setNamedItem(attr2);
    }
    
    // Move all the children
    while (element.hasChildNodes()) {
        element2.appendChild(element.getFirstChild());
    }
    
    // Replace the old node with the new node
    element.getParentNode().replaceChild(element2, element);

 Related Examples
e531. Getting a DOM Element by Id
e532. Visiting All the Elements in a DOM Document

See also: Adding and Removing Nodes    Element Attributes    Getting Nodes    Text Nodes    XPath   


© 2002 Addison-Wesley.