码迷,mamicode.com
首页 > 其他好文 > 详细

dom4j解析器sax解析xml文件

时间:2018-06-11 01:55:36      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:anim   image   yellow   one   gpo   class   org   enc   lib   

1.使用dom4j解析器解析xml

***解析器dom4j是由dom4j组织提供的,针对xml进行解析。dom4j不是Javase的一部分,使用时需要导入dom4j的jar包(官网下载)

  在eclipse里,复制jar包,然后新建文件夹lib粘贴进入,然后单击鼠标右键jar包----->build path----->add to build path

  看到jar包变成奶瓶样子,表示导入成功。

* 得到document对象

      SAXReader reader=new SAXReader();

      Document document=reader.read(url);

*document对象的父接口是Node

      **如果在document对象里找不到想要的方法,就去Node里面去找。

*document里的方法getRootElement():得到根节点,并返Element

*Element也是一个接口,父接口是Node

       **Element和Node里的方法

        getParent():获取父节点

        addElement():添加标签

需求:查询所有name元素里的值

代码:

animal.xml

<?xml version="1.0" encoding="UTF-8"?>
<animal>
<cat>
<name>汤姆</name>
<color>black</color>
<age>10</age>
</cat>
<cat>
<name>丑小鸭</name>
<color>yellow</color>
<age>15</age>
</cat>
</animal>

 dom4j.java

package  example4;

import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

class dom4j{
    public static void main(String[] args) throws Exception {
        selectName();
    }

//查询第一个name元素的值

public static void selectOne() throws Exception {
        SAXReader saxreader = new SAXReader();
        Document document = saxreader.read("src/example4/animal.java");
        Element root = document.getRootElement();
        Element cat = root.element("cat");
        Element name = cat.element("name");
        String s=name.getText();
        System.out.println(s);
    }

 

// 获取第二个name元素里的值
    public static void selectSecond() throws Exception {
        SAXReader saxreader=new SAXReader();
        Document document=saxreader.read("src/example4/animal.xml");
        Element root=document.getRootElement();
        List<Element> list=root.elements("cat");
        Element cat2=list.get(1);
        Element name2=cat2.element("name");
        String s=name2.getText();
        System.out.println(s);
    }


    // 查询xml中所有name元素的值
        public static void selectName() throws Exception {
            // 创建解析器
            SAXReader saxreader = new SAXReader();
            //得到document对象
            Document document=saxreader.read("src/example4/animal.xml");
            //得到根节点
            Element root=document.getRootElement();
            //得到cat结点
            List<Element> list=root.elements("name");
            //得到cat元素下的name元素
            for (Element element: list) {
            //element是每一个cat元素
            //得到cat下面的name元素
            Element name1=element.element("name");
            String s=name1.getText();
            System.out.println(s);    
        }
    }
}

 

好文要顶 关注我 收藏该文 技术分享图片 技术分享图片

dom4j解析器sax解析xml文件

标签:anim   image   yellow   one   gpo   class   org   enc   lib   

原文地址:https://www.cnblogs.com/aasu/p/9131248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!