Dom解析xml
xml文件(置于src目录下)
<span style="font-family:Comic Sans MS;font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>Java编程思想</name>
<author>埃克尔</author>
<year>2007</year>
<price>73</price>
</book>
<book id="2">
<name>安徒生童话</name>
<year>2004</year>
<price>77</price>
<language>English</language>
</book>
</bookstore></span>
java代码
<span style="font-family:Comic Sans MS;font-size:18px;">package com.tang.dom;
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 XmlAnalysis {
public static void main(String args[]){
//创建DocumentBuilderFactory对象
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
//通过工厂获取DocumentBuilder对象
db = dbf.newDocumentBuilder();
//传入一XML文档的url,返回一个Document对象
Document document = db.parse("books.xml");
//api:按文档顺序返回包含在文档中且具有给定标记名称的所有元素的 节点结合
NodeList nodeLise = document.getElementsByTagName("book");
for(int i=0;i<nodeLise.getLength();i++)
{
Node node=nodeLise.item(i);
//获取节点属性
NamedNodeMap attributes = node.getAttributes();
for(int j=0;j<attributes.getLength();j++){
Node attrNode = attributes.item(j);
System.out.println("属性名字:"+attrNode.getNodeName()+" 属性值:"+attrNode.getNodeValue());
}
//获取节点名字和属性
NodeList childNodes = node.getChildNodes();
for(int c=0;c<childNodes.getLength();c++){
Node cNode = childNodes.item(c);
if (cNode.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("节点名字: "+cNode.getNodeName()+ "节点值:"+cNode.getFirstChild().getNodeValue());
}
}
System.out.println("=============================================");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}</span>