DOM:
Document Object Model
DOM模型就是把XML文档作为一个树形结构,从根结点开始,每个节点都可以包含任意个字节点。
用Java解析XML时,
Document代表整个XML文档
Element表示元素
Attribute:属性
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(XML_URL);
Element root = doc.getDocumentElement();
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数据结构
- 解析速度慢,内存占用大
原文地址:https://www.cnblogs.com/csj2018/p/11379284.html
时间: 2024-10-01 22:00:10