1、DOM4j读写xml实例 所需jar文件dom4j-1.6.1.jar
2、读xml文件名 test.xml
<?xml version="1.0" encoding="UTF-8"?>
<university name="pku">
<college name="c1">
<class name="class1">
<student name="stu1" sex='male' age="21" />
<student name="stu2" sex='female' age="20" />
<student name="stu3" sex='female' age="20" />
</class>
<class name="class2">
<student name="stu4" sex='male' age="19" />
<student name="stu5" sex='female' age="20" />
<student name="stu6" sex='female' age="21" />
</class>
</college>
<college name="c2">
<class name="class3">
<student name="stu7" sex='male' age="20" />
</class>
</college>
<college name="c3">
</college>
</university>
3、读xml
public static void readXml() throws DocumentException{
SAXReader reader = new SAXReader();
InputStream in= ParserXML.class.getResourceAsStream("test.xml");
Document doc=reader.read(in);
Element root=doc.getRootElement();
readNode(root);
}
public static void readNode(Element root){
if(root==null){return ;}
//读取属性
List<Attribute> attributesList=root.attributes();
for(Attribute attr:attributesList){
System.out.println(attr.getValue());
}
//读取元素
List<Element> elementList=root.elements();
for(Element elem:elementList){
readNode(elem);
}
}
4、生成xml
public static void write() throws IOException{
Document doc=DocumentHelper.createDocument();
Element book=doc.addElement("book");
book.addAttribute("name", "书籍");
Element english=book.addElement("english");
english.addAttribute("name", "英语");
english.setText("aabbccdd");
Element math=book.addElement("math");
math.addAttribute("name", "数学");
math.setText("11223344");
File file =new File("src/com/demo/test/book.xml");
if(file.exists()){
file.delete();
}
file.createNewFile();
XMLWriter out =new XMLWriter(new FileWriter(file));
out.write(doc);
out.flush();
out.close();
}
5、生成的xml文件 book.xml
<?xml version="1.0" encoding="UTF-8"?>
<book name="书籍"><english name="英语">aabbccdd</english><math name="数学">11223344</math></book>