Java examples for XML:DOM Element
replace XML Element
/**/*from ww w . j ava2 s.co m*/ * Copyright 2012 Sven Ewald * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.XMLConstants; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main{ /** * @param previous * @param newNode */ public static void replaceElement(final Element previous, final Element newNode) { assert previous.getParentNode() != null; Element parent = (Element) previous.getParentNode(); Document document = getOwnerDocumentFor(parent); ensureOwnership(document, newNode); parent.replaceChild(newNode, previous); } /** * @param documentOrElement * @return document that owns the given node */ public static Document getOwnerDocumentFor(final Node documentOrElement) { if (Node.DOCUMENT_NODE == documentOrElement.getNodeType()) { return (Document) documentOrElement; } return documentOrElement.getOwnerDocument(); } /** * @param ownerDocument * @param node */ public static void ensureOwnership(final Document ownerDocument, final Node node) { if (ownerDocument != node.getOwnerDocument()) { ownerDocument.adoptNode(node); } } }