The Java Developers Almanac 1.4


Order this book from Amazon.

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

e525. Copying a Subtree of Nodes in a DOM Document

    // Obtain an element; the following method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", false);
    NodeList list = doc.getElementsByTagName("entry");
    Element element = (Element)list.item(0);
    
    // Make a copy of the element, including any child nodes
    Element dup = (Element)element.cloneNode(true);
    
    // Insert the copy immediately after the cloned element
    element.getParentNode().insertBefore(dup, element.getNextSibling());
This is the sample input for the example:
    <root>
        <entry attr="value">
            a<i>b</i>c
        </entry>
    </root>
This is the resulting XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        <entry attr="value">
            a<i>b</i>c
        </entry><entry attr="value">
            a<i>b</i>c
        </entry>
    </root>

 Related Examples
e524. Visiting All the Nodes in a DOM Document
e526. Copying a Subtree of Nodes from One DOM Document to Another

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


© 2002 Addison-Wesley.