dom4j读取xml文件 简单例子

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ReadXML {
 static List list = new ArrayList();

 public static void getListFromXml() {
  InputStream inputStream = null;
  Document doc = null;
  SAXReader reader = new SAXReader();
  try {
   inputStream = Thread.currentThread().getContextClassLoader()
     .getResourceAsStream("config.xml");
   doc = reader.read(inputStream);
   Element root = doc.getRootElement();
   list = root.elements("field");

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  getListFromXml();
  for (Iterator it = list.iterator();it.hasNext();) {
   System.out.println(((Element)it.next()).getText());
  }
 }
}

 

---------------------------------------------

<?xml version="1.0" encoding = "UTF-8" ?>
<config>
 <field>hello</field>
 <field>well</field>
 <field>bye</field>
</config>

--------------------------------------------

 

你可能感兴趣的:(dom4j)