Java 怎么准备直接XML节点

2019年8月8日20:36:30Java 怎么准备直接XML节点已关闭评论 415 1384字阅读4分36秒

1.简介

Java 怎么准备直接XML节点?——请看下文。

2.示例代码

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

import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main{
    public static Node prepareDirectNode(Document document, Node root,
            String name, String[] elementOrder) {
        List<Node> nodes = DocumentUtility.getDirectChildNodes(root, name);
        Node node = null;
        if (nodes.size() > 0) {
            node = nodes.get(0);
        } else {
            
            node = document.createElement(name);

            
            Node targetNode = null;
            boolean foundNewNodePosition = false;
            for (String elementName : elementOrder) {
                if (!foundNewNodePosition) {
                    if (elementName.equals(name)) {
                        foundNewNodePosition = true;
                    }
                } else {
                    targetNode = getDirectChildNode(root, elementName);
                    if (targetNode != null) {
                        break;
                    }
                }
            }

            
            root.insertBefore(node, targetNode);
        }

        return node;
    }
    public static List<Node> getDirectChildNodes(Node node, String name) {
        LinkedList<Node> nodes = new LinkedList<Node>();

        NodeList childList = node.getChildNodes();
        for (int childIndex = 0; childIndex < childList.getLength(); childIndex++) {
            Node child = childList.item(childIndex);
            if (child.getNodeName().equals(name)) {
                nodes.add(child);
            }
        }

        return nodes;
    }
    public static Node getDirectChildNode(Node node, String name) {
        Node targetNode = null;

        List<Node> nodes = getDirectChildNodes(node, name);
        if (nodes.size() == 1) {
            targetNode = nodes.get(0);
        }

        return targetNode;
    }
}

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