• 利用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());
        }
      }
    }

      

     

      

  • 相关阅读:
    linux基础学习-8.1-无法远程连接服务器常见原因
    schema约束文档 根元素的写法
    用双重for循环生成九九乘法表
    Random类、String类的一些常用方法
    Random()方法结合Scanner类实现猜数游戏
    使用System类和Date类来计算自己从出生到现在度过了多少时间
    获取map集合中键和值的三种方式
    斗地主实现洗牌发牌功能
    集合框架<一>
    动手动脑2
  • 原文地址:https://www.cnblogs.com/charging-for-ycp/p/6582607.html
Copyright © 2020-2023  润新知