Element parentElement = doc.createElement("parent"); // create a new parent element Element childElement = doc.createElement("child"); // create a new child element parentElement.appendChild(childElement); // add the child element to the parent element
Element existingParent = doc.getElementById("existingParent"); // get an existing parent element Element newParent = doc.createElement("newParent"); // create a new parent element newParent.appendChild(existingParent); // add the existing parent to the new parentIn both examples, the Element appendChild method is used to add a new child element to an existing Element node. The package library for this method is org.w3c.dom.Element.