Java 怎么将根位于指定节点的XML树打印到指定的打印流

2019年7月24日22:45:16Java 怎么将根位于指定节点的XML树打印到指定的打印流已关闭评论 489 1705字阅读5分41秒

1.简介

Java 怎么将根位于指定节点的XML树打印到指定的打印流?——请看下文。

2.示例代码

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


import java.io.PrintStream;
import org.w3c.dom.Attr;
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 {

    private static void printXMLTreeRec(Node n, PrintStream out, String pre) {
        final String NO_EDGE = "  ";
        final String STRAIGHT_EDGE = "? ";
        final String CHILD_EDGE = "??";
        final String LAST_CHILD_EDGE = "??";

        
        NodeList children = n.getChildNodes();
        NamedNodeMap attributes = n.getAttributes();

        
        Node attr;
        if (attributes != null) {
            for (int index = 0; index < attributes.getLength(); index++) {
                attr = attributes.item(index);

                
                if (index + 1 == children.getLength()
                        && children.getLength() == 0) {
                    out.print(pre + LAST_CHILD_EDGE);
                    printXMLNode(attr, out);
                    printXMLTreeRec(attr, out, pre + NO_EDGE);
                } else {
                    out.print(pre + CHILD_EDGE);
                    printXMLNode(attr, out);
                    printXMLTreeRec(attr, out, pre + STRAIGHT_EDGE);
                }
            }
        }

        
        Node child;
        for (int index = 0; index < children.getLength(); index++) {
            child = children.item(index);

            
            if (index + 1 == children.getLength()) {
                out.print(pre + LAST_CHILD_EDGE);
                printXMLNode(child, out);
                printXMLTreeRec(child, out, pre + NO_EDGE);
            } else {
                out.print(pre + CHILD_EDGE);
                printXMLNode(child, out);
                printXMLTreeRec(child, out, pre + STRAIGHT_EDGE);
            }
        }
    }

    
    public static void printXMLNode(Node n, PrintStream out) {
        switch (n.getNodeType()) {
        case Node.DOCUMENT_NODE:
            out.println("DOC_ROOT");
            break;

        case Node.ELEMENT_NODE:
            out.println("<" + ((Element) n).getTagName() + ">");
            break;

        case Node.ATTRIBUTE_NODE:
            out.println("@" + ((Attr) n).getName());
            break;

        case Node.TEXT_NODE:
            out.println("\"" + ((Text) n).getWholeText().trim() + "\"");
            break;

        case Node.COMMENT_NODE:
            out.println("COMMENT: \"" + n.getTextContent().trim() + "\"");
            break;

        default:
            out.println("Unknown node type: " + n.getNodeType());
        }
    }
}

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