简单的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student name="张三">
<age>20</age>
</student>
<student name="李四">
</student>
</students>
1、解析上面一段xml文件首先获取Document对象,Document对象代表整个xml文档
public Document getDocument(String fileName){
SAXReader reader=new SAXReader();
Document document=null;
try {
document=reader.read(new File(fileName));
} catch (DocumentException e) {
e.printStackTrace();
}
return document;
}
2、解析节点元素,可以有很多中选择方法,下面是其中的两种
2.1 迭代
获取根节点后,迭代元素
//获取根节点
public Element getRootElement(Document document){
return document.getRootElement();
}
//迭代元素
Element root=parser.getRootElement(document);
Iterator<Element> it=root.elementIterator();
while(it.hasNext()){
System.out.println(it.next().attributeValue("name"));
}
2.2 类继承VisitorSupport,VisitorSupport有很多中方法,可以选择性的重写
private static class NodeVistor extends VisitorSupport{
@Override
public void visit(Element node) {
super.visit(node);
if(!node.isRootElement()){
System.out.println(node.getName()+":"+node.getData());
}
}
// @Override
// public void visit(Attribute node) {
// System.out.println(node.getName()+":"+node.getValue());
// }
}
//通过accept方法调用
root.accept(new Dom4jXMLParser.NodeVistor());
3.访问某一元素节点,可以使用XPath
List<Element> element=(List<Element>) document.selectNodes("//students/student");
for(Element e:element){
System.out.println(e.getName());
}
4、创建xml文档
private Document createDocument(){
Document document=DocumentHelper.createDocument();
Element root=document.addElement("students");
Element student=root.addElement("student");
student.addAttribute("name", "张三");
return document;
}
//写入xml
private void writeXML(Document document) {
XMLWriter writer=null;
try {
OutputFormat format = OutputFormat.createPrettyPrint();//格式化
format.setEncoding("UTF-8");//设置编码
writer= new XMLWriter(new FileOutputStream(new File("d:\\1.xml")),format);
writer.write(document);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(writer!=null)
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}