XML解析之dom4j

1.使用dom4j技术解析XML

public class Dom4jTest {
    public static void main(String[] args) {
        //1.创建SAXReader对象
        SAXReader saxReader=new SAXReader();

        try {
            //2.通过SAXReader对象加载book.xml文件,获取Document对象
            Document document = saxReader.read(new File("/home/yaming/Desktop/workspace/javatech-parent/xml/src/main/resources/books.xml"));
            //3.通过getRootElement方法 获取根节点
            Element bookStore =  document.getRootElement();
            //4.通过elementIterator 获取迭代器(根节点的第一层子节点)
            Iterator iterator=bookStore.elementIterator();
            //5.遍历迭代器,获取根节点下的信息(根节点的子节点)
            while (iterator.hasNext()){
                System.out.println("------------开始遍历某一根书--------");
                Element book = (Element) iterator.next();//强制类型转换
                //(1).通过attributes 获取book的属性名名和属性值(子节点下的子节点)
                List<Attribute> bookAttrs=book.attributes();
                for (Attribute attr:bookAttrs){
                    //获取属性名
                    String name=attr.getName();
                    //获取属性值
                    String value=attr.getValue();
                    System.out.println("属性名:"+name+"属性值:"+value);
                }

                //(2).通过elementIterator 获取book节点的子节点的节点名和节点值
                Iterator it=book.elementIterator();
                while (it.hasNext()){
                    Element bookChild= (Element) it.next();
                    //获取节点名
                    String name=bookChild.getName();
                    //获取节点值
                    String value=bookChild.getStringValue();
                    System.out.println("节点名:"+name+"节点值:"+value);
                }
                System.out.println("------------开始遍历某一根书--------");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
}

2.说明:

#1.引入jar包
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
#2.编程
##1.
创建SAXReader对象
##2.
通过SAXReader对象加载book.xml文件,获取Document对象
##3.
通过getRootElement方法 获取根节点
##4.
通过elementIterator 获取迭代器(根节点的子节点)
##5.
遍历迭代器,获取根节点下的信息(根节点的子节点)
####(1).
 通过attributes 获取book的属性名名和属性值(子节点下的子节点)
 ####(2)
 通过elementIterator 获取book节点的子节点的节点名和节点值

3.其他解析xml的技术,dom,jdom,sax等。以后再补

猜你喜欢

转载自www.cnblogs.com/inspred/p/8908450.html