Java 怎么替换XML元素

2019年7月26日23:26:54Java 怎么替换XML元素已关闭评论 476 1141字阅读3分48秒

1.简介

Java 怎么替换XML元素?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 
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{
    
    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);
    }
    
    public static Document getOwnerDocumentFor(final Node documentOrElement) {
        if (Node.DOCUMENT_NODE == documentOrElement.getNodeType()) {
            return (Document) documentOrElement;
        }
        return documentOrElement.getOwnerDocument();
    }
    
    public static void ensureOwnership(final Document ownerDocument,
            final Node node) {
        if (ownerDocument != node.getOwnerDocument()) {
            ownerDocument.adoptNode(node);
        }
    }
}

 
继续阅读
编程十万个怎么办