java中使用dom4j读xml文件简单教程

需要dom4j.jar文件 ,自行下载。

test.xml

  1: <?xml version="1.0" encoding="gbk"?>
  2: 
  3: <students>
  4:   <person sex="男" age="21">
  5:     <id>1</id>
  6:     <name>章治鹏</name>
  7:     <homepage>http://blog.csdn.net/tonyzzp</homepage>
  8:   </person>
  9:   <person age="20">
 10:     <id>2</id>
 11:     <name>徐雄皓</name>
 12:     <homepage boolean="false">http://www.xxh.com</homepage>
 13:   </person>
 14: </students>
 
 
XMLStudentsParam.java
  1: package org.zzp.common.xml.dom4j;
  2: 
  3: public enum XMLStudentsParam {
  4: 	id,name,homepage,sex,age
  5: }

 

 

Dom4jReadDemo.java

  1: package org.zzp.common.xml.dom4j;
  2: 
  3: import java.util.Iterator;
  4: import java.util.List;
  5: 
  6: import org.dom4j.Attribute;
  7: import org.dom4j.Document;
  8: import org.dom4j.DocumentException;
  9: import org.dom4j.Element;
 10: import org.dom4j.io.SAXReader;
 11: 
 12: public class Dom4jReadDemo {
 13:  public static void main(String[] args) {
 14:   try {
 15:    Document doc=new SAXReader().read("test.xml");
 16:    Element root=doc.getRootElement();
 17:    System.out.println("根节点名:"+root.getName());
 18:    List<Element> students=root.elements();
 19:    System.out.println("共有学生数"+students.size()+"\n");
 20:    //遍历每个学生
 21:    for(Iterator<Element> it= students.iterator();it.hasNext();){
 22:     Element student=(Element)it.next();
 23:     List<Element> student_s=student.elements();
 24:     //遍历每个学生的子标签
 25:     for(Iterator<Element> its=student_s.iterator();its.hasNext();){
 26:      Element param=(Element)its.next();
 27:      switch(XMLStudentsParam.valueOf(param.getName())){
 28:      case name:
 29:       System.out.print("姓名:");
 30:       break;
 31:      case id:
 32:       System.out.print("编号:");
 33:       break;
 34:      case homepage:
 35:       System.out.print("主页:");
 36:       if (param.attribute("boolean")!=null && !param.attribute("boolean").getText().equals("true")) {
 37:        System.out.print("(网页未经验证)");
 38:       }
 39:       break;
 40:      }
 41:      System.out.println(param.getText());
 42:     }
 43:     //遍历每个学生的属性
 44:     for(Iterator<Attribute> ita=student.attributeIterator();ita.hasNext();){
 45:      Attribute a=(Attribute)ita.next();
 46:      switch(XMLStudentsParam.valueOf(a.getName())){
 47:      case sex:
 48:       System.out.print("性别:");
 49:       break;
 50:      case age:
 51:       System.out.print("年龄:");
 52:       break;
 53:      }
 54:      System.out.println(a.getText());
 55:     }
 56:     System.out.println();
 57:    }
 58:   } catch (DocumentException e) {
 59:    // TODO Auto-generated catch block
 60:    e.printStackTrace();
 61:   }
 62:  }
 63: }
posted @ 2010-03-25 21:20  石沉溪  阅读(1731)  评论(0编辑  收藏  举报