Java 怎么实现如果文档不为空,则追加新的XML元素

2019年7月25日22:39:19Java 怎么实现如果文档不为空,则追加新的XML元素已关闭评论 464 1760字阅读5分52秒

1.简介

Java 怎么实现如果文档不为空,则追加新的XML元素?——请看下文。

2.示例代码

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


import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
    public static Element appendNewElementIfNotNull(Document document,
            Element parent, Enum el, Object content) {
        return appendNewElementIfNotNull(document, parent, el, content,
                null);
    }

    public static Element appendNewElementIfNotNull(Document document,
            Element parent, Enum el, Object content, String namespace) {
        return appendNewElementIfNotNull(document, parent, el.toString(),
                content, namespace);
    }

    public static Element appendNewElementIfNotNull(Document document,
            Element parent, String element, Object content) {
        return appendNewElementIfNotNull(document, parent, element,
                content, null);
    }

    public static Element appendNewElementIfNotNull(Document document,
            Element parent, String element, Object content, String namespace) {
        if (content == null)
            return parent;
        return appendNewElement(document, parent, element, content,
                namespace);
    }

    public static Element appendNewElement(Document document,
            Element parent, Enum el) {
        return appendNewElement(document, parent, el.toString());
    }

    public static Element appendNewElement(Document document,
            Element parent, String element) {
        Element child = document.createElement(element);
        parent.appendChild(child);
        return child;
    }

    public static Element appendNewElement(Document document,
            Element parent, String element, Object content) {
        return appendNewElement(document, parent, element, content, null);
    }

    public static Element appendNewElement(Document document,
            Element parent, String element, Object content, String namespace) {
        Element childElement;
        if (namespace != null) {
            childElement = document.createElementNS(namespace, element);
        } else {
            childElement = document.createElement(element);
        }

        if (content != null) {
            
            
            
            childElement.appendChild(document.createTextNode(content
                    .toString()));
        }

        parent.appendChild(childElement);
        return childElement;
    }
}

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