常见的解析XML方式可分为两大类:
(一)JDK自带的解析方式
- DOM解析
- SAX解析
(二)通过外部jar包解析
- JDOM解析
- DOM4J解析
下面依次介绍通过每种方式对XML文档解析
DOM解析方式的步骤
1. 创建一个documentbuilderfactory对象
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
2.通过documentbuilderfactory创建DocumentBuilder
db=dbf.newDocmentBuilder();
3. 通过DocumentBuilder的parse获取文件
Document doc=db.parse(“books.xml”);(一定要是org.w3c包下的Document)
得到Document对象之后,我们就可以通过doc来完成对xml文档的解析工作了
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>安徒生童话</name>
<author>安徒生</author>
<price>69</price>
</book>
<book id="2">
<name>绝世唐门</name>
<author>唐家三少</author>
<price>88</price>
<language>English</language>
</book>
</bookstore>
解析XML文档
public static void resXml()throws Exception{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc=db.parse("books.xml");
NodeList books = doc.getElementsByTagName("book");
System.out.println(books.getLength());
//遍历每一个节点(每一本书)
for(int i=0;i<books.getLength();i++){
System.out.println("第"+(i+1)+"本书");
Node book = books.item(i);
//每个节点的属性
NamedNodeMap attrs=book.getAttributes();
for(int j=0;j<attrs.getLength();j++){
Node d = attrs.item(j);
System.out.println(d.getNodeName()+":"+d.getNodeValue());
}
//获取book的子节点
NodeList bookAttr=book.getChildNodes();
//System.out.println(bookAttr.getLength());
//输出每个子节点的内容
for(int k=0;k<bookAttr.getLength();k++){
Node node = bookAttr.item(k);
//在xml中换行的空格都代表节点
//所以我们输出内容不是空格的节点
if(node.getNodeType()!=3){
System.out.println(node.getNodeName()+":"+node.getFirstChild().getNodeValue());
}
}
}
}
解析结果: