Java 怎么将单个节点导入XML文档

2019年8月7日21:09:53Java 怎么将单个节点导入XML文档已关闭评论 346 1854字阅读6分10秒

1.简介

Java 怎么将单个节点导入XML文档?——请看下文。

2.示例代码

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


import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;

public class Main {
    
    public static Node importNode(Node parent, Node child) {
        return importNode(parent, child, true);
    }

    
    public static Node importNode(Node parent, Node child, boolean doappend) {

        Attr attr;
        int i;
        NamedNodeMap attributes;
        Node copy = null;
        NodeList children = null;
        String tagName = null;
        Document doc = parent.getOwnerDocument();

        try {
            children = child.getChildNodes();
        } catch (DOMException e) {
        }

        switch (child.getNodeType()) {
        case Node.CDATA_SECTION_NODE:
            copy = doc.createCDATASection(((CDATASection) child).getData());
            break;
        case Node.COMMENT_NODE:
            copy = doc.createComment(((Comment) child).getData());
            break;
        case Node.DOCUMENT_FRAGMENT_NODE:
            copy = doc.createDocumentFragment();
            break;
        case Node.ELEMENT_NODE:
            tagName = ((Element) child).getTagName();
            copy = doc.createElement(tagName);
            if ((attributes = child.getAttributes()) != null) {
                for (i = 0; i < attributes.getLength(); i++) {
                    attr = (Attr) attributes.item(i);
                    ((Element) copy).setAttribute(attr.getName(),
                            attr.getValue());
                }
            }
            break;
        case Node.ENTITY_REFERENCE_NODE:
            copy = doc.createEntityReference(((EntityReference) child)
                    .getNodeName());
            break;
        case Node.PROCESSING_INSTRUCTION_NODE:
            copy = doc.createProcessingInstruction(
                    ((ProcessingInstruction) child).getTarget(),
                    ((ProcessingInstruction) child).getData());
            break;
        case Node.TEXT_NODE:
            copy = doc.createTextNode(((Text) child).getData());
            break;
        default:
            return null;

        }

        if (children != null) {
            for (i = 0; i < children.getLength(); i++) {
                if (children.item(i) != null) { 
                    importNode(copy, children.item(i));
                }
            }
        }
        if (doappend) {
            parent.appendChild(copy);
        }

        return copy;

    }
}

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