廖雪峰Java14Java操作XML和JSON-1XML-2DOM

我与影子孤独终老i 提交于 2019-11-27 21:53:40
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class DomSample {
    static final  String XML_URL = "http://rss.sina.com.cn/tech/internet/home28.xml";
    public static void main(String[] args) throws Exception{
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(XML_URL);
        printNode(doc,0);
    }
    static void printNode(Node n, int indent){
        for(int i=0;i<indent;i++){
            System.out.print(' ');
        }
        switch (n.getNodeType()){
            case Node.DOCUMENT_NODE:
                System.out.println("Document:"+n.getNodeName());
                break;
            case Node.ELEMENT_NODE:
                System.out.println("Element:"+n.getNodeName());
                break;
            case Node.TEXT_NODE:
                System.out.println("Text:"+n.getNodeName()+"="+n.getNodeValue());
                break;
            case Node.ATTRIBUTE_NODE:
                System.out.println("Attr:"+n.getNodeName()+"="+n.getNodeValue());
                break;
            case Node.CDATA_SECTION_NODE:
                System.out.println("CDATA:"+n.getNodeName()+"="+n.getNodeValue());
                break;
            case Node.COMMENT_NODE:
                System.out.println("Commment:"+n.getNodeName()+"="+n.getNodeValue());
                break;
            default:
                System.out.println("NodeType:"+n.getNodeType()+",NodeName:"+n.getNodeName());
        }
        for(Node child=n.getFirstChild();child != null;child=child.getNextSibling()){
            printNode(child,indent+1);
        }
    }
}

总结:

Java DOM API:

  • 将XML解析为DOM
  • 可在内存中完整表示XML数据结构
  • 解析速度慢,内存占用大
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!