zoukankan      html  css  js  c++  java
  • 利用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());
        }
      }
    }

      

     

      

  • 相关阅读:
    MySQL组提交(group commit)
    MySQL 热快问题解决
    Mysql 高可用集群PXC
    向量的点积(标量积、内积)
    BitmapData.threshold()方法
    Unity 自定义导入时切割Sprite
    匀变速直线运动的速度与位移的关系
    1.1.2 三角形余弦定理
    ccc切割刚体
    Unity 获取指定资源目录下的所有文件
  • 原文地址:https://www.cnblogs.com/charging-for-ycp/p/6582607.html
Copyright © 2011-2022 走看看