对xml文件的生成和解析方式中,主要有四种方式,分别是DOM、SAX、JDOM、DOM4J,前两种是官方提供的解析方式,不需要引入其它的jar包,其中第一种与平台无关,在非Java平台也能使用,第二种由Java平台提供,是基于事件驱动的解析。后两种方式是非官方的方式,需要引入jar包才能使用。
DOM4J是如今使用最广泛的方式,它的性能优异并且灵活性好,使用时引入dom4j的jar包即可。
1. 生成xml文件
public class GenerateXML {
public static void main(String[] args) throws IOException {
//创建document
Document document=DocumentHelper.createDocument();
//创建根节点bookstore
Element bookstore=document.addElement("bookstore");
//创建第一个子节点book
Element book1=bookstore.addElement("book");
//增加book的属性
book1.addAttribute("id", "B0001");
//增加book的子节点
book1.addElement("name").setText("linux");
book1.addElement("author").setText("uncle bird");
book1.addElement("year").setText("2000");
book1.addElement("language").setText("English");
//创建第二个子节点book
Element book2=bookstore.addElement("book");
//增加book的属性
book2.addAttribute("id", "B0002");
//增加book的子节点
book2.addElement("name").setText("java");
book2.addElement("author").setText("Bob");
book2.addElement("year").setText("2010");
book2.addElement("language").setText("Chinese");
//创建文件类
File file=new File("bookstore.xml");
//设置输入格式
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
//创建xmlwriter
XMLWriter writer=new XMLWriter(new FileOutputStream(file), format);
//设置转义为false,此时不用转义,默认为true
writer.setEscapeText(false);
//生成xml文件
writer.write(document);
writer.close();
}
}
生成的bookstore.xml文件内容为:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="B0001">
<name>linux</name>
<author>uncle bird</author>
<year>2000</year>
<language>English</language>
</book>
<book id="B0002">
<name>java</name>
<author>Bob</author>
<year>2010</year>
<language>Chinese</language>
</book>
</bookstore>
2. 解析xml文件
public class ParseXML {
public static void main(String[] args) throws DocumentException {
//创建SAXReader对象
SAXReader saxReader=new SAXReader();
//读入xml文件,获得document对象
Document document=saxReader.read(new File("bookstore.xml"));
//获得根节点元素
Element bookstore=document.getRootElement();
//获取bookstore的迭代器Iterator对象
Iterator iterator=bookstore.elementIterator();
//对所有书进行遍历
while(iterator.hasNext()){
System.out.println("-----------");
//获取每本书
Element book=(Element)iterator.next();
//获取每本书的属性列表
List<Attribute> attributes=book.attributes();
//遍历属性并输出
for (Attribute attribute : attributes) {
System.out.println(attribute.getName()+":"+attribute.getValue());
}
//获取书的子节点迭代器
Iterator iterator2=book.elementIterator();
//对书的子节点遍历并输出
while(iterator2.hasNext()){
Element attr=(Element)iterator2.next();
System.out.println(attr.getName()+":"+attr.getStringValue());
}
}
}
}
输出结果为:
-----------
id:B0001
name:linux
author:uncle bird
year:2000
language:English
-----------
id:B0002
name:java
author:Bob
year:2010
language:Chinese