利用dom4j来解析xml文件

首先需要导入两个dom4j用到的jar包:dom4j-1.6.1.jar、jaxen-1.1.1.jar

<?xml version="1.0" encoding="UTF-8"?>
<main>
  <first>
    <first1>1</first1>
    <first2>
      <first21>2</first21>
    </first2>
  </first>
  <second>
    <second1>123</second1>
  </second>
</main>

第一步:创建.xml文件

  Document docu=new DocumentHelper.creatDocument();

  Element mainElement= docu.addElement("main");

  Element firstChild=mainElement.addElement("first");

  Element secondChild=mainElement.addElment("second")

  Element first1Child=firstChild.addElement("first1");

  //为标签《first1》设置文本值

  first1Child.setText("1");

  Element first2Child=firstChild.addElement("first2");

  ....剩下的都是重复的代码,暂时忽略

  //将上面元素写入新创建的abc.xml文件中

  Writer file=new FileWriter("d:/abc.xml");

  XMLWriter xmlWriter=new XMLWriter(file);

  xmlWriter.write(docu);

  xmlWriter.close();

第二步:利用dom4j来读取abc.xml文件

  这里为了方便,我采用递归的方法去解析xml文件,这样代码量可以少一些,不过,效率方面好像会偏低一些,这就是我们为什么尽量少用递归的一个原因

public class Test1 {
  public static void main(String[] args) {
    SAXReader sr=new SAXReader();
    Document docu;
    try {
      docu = sr.read(new File(d:/abc.xml));
      Element ele=docu.getRootElement();
      //调用解析xml方法:parseXML(File file)
      parseXMLFile(ele);
    } catch (DocumentException e) {
      e.printStackTrace();
    }
  }
  public static void parseXMLFile(Element ele){
    @SuppressWarnings("unchecked")
    Iterator<Element> ite=ele.elementIterator();
    System.out.println("名字:"+ele.getName()+"值:"+ele.getText());
    while(ite.hasNext()){
    parseXMLFile(ite.next());
    }
  }
}

  

 

  

原文地址:https://www.cnblogs.com/charging-for-ycp/p/6582607.html