Java 怎么打印指定的节点,然后打印其所有子XML元素

2019年8月6日22:16:42Java 怎么打印指定的节点,然后打印其所有子XML元素已关闭评论 509 1529字阅读5分5秒

1.简介

Java 怎么打印指定的节点,然后打印其所有子XML元素?——请看下文。

2.示例代码

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



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 void printDOM(Node node) {
        int type = node.getNodeType();
        switch (type) {
        
        case Node.DOCUMENT_NODE: {
            System.out.println("<?xml version=\"1.0\" ?>");
            printDOM(((Document) node).getDocumentElement());
            break;
        }

        
        case Node.ELEMENT_NODE: {
            System.out.print("<");
            System.out.print(node.getNodeName());
            NamedNodeMap attrs = node.getAttributes();
            for (int i = 0; i < attrs.getLength(); i++) {
                Node attr = attrs.item(i);
                System.out.print(" " + attr.getNodeName().trim() + "=\""
                        + attr.getNodeValue().trim() + "\"");
            }
            System.out.println(">");

            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++)
                    printDOM(children.item(i));
            }

            break;
        }

        
        case Node.ENTITY_REFERENCE_NODE: {
            System.out.print("&");
            System.out.print(node.getNodeName().trim());
            System.out.print(";");
            break;
        }

        
        case Node.CDATA_SECTION_NODE: {
            System.out.print("<![CDATA[");
            System.out.print(node.getNodeValue().trim());
            System.out.print("]]>");
            break;
        }

        
        case Node.TEXT_NODE: {
            System.out.print(node.getNodeValue().trim());
            break;
        }

        
        case Node.PROCESSING_INSTRUCTION_NODE: {
            System.out.print("<?");
            System.out.print(node.getNodeName().trim());
            String data = node.getNodeValue().trim();
            {
                System.out.print(" ");
                System.out.print(data);
            }
            System.out.print("?>");
            break;
        }
        }

        if (type == Node.ELEMENT_NODE) {
            System.out.println();
            System.out.print("</");
            System.out.print(node.getNodeName().trim());
            System.out.print('>');
        }
    }
}

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