通过Java读取xml文件内容

读取XML中的内容就需要对XML进行解析,目前对XML进行解析的方法分为四种

 

下面解析的方法是DOM4J,需要下载jar包dom4j:https://dom4j.github.io/

package com.zyb.xml;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class testXml {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        //1.创建SAXReader对象用于读取xml文件
        SAXReader reader = new SAXReader();
        //2.读取xml文件,获得Document对象
        Document doc = reader.read(new File("src/book.xml"));
        //3.获取根元素
        Element root = doc.getRootElement();
        //4.获取根元素下的所有子元素(通过迭代器)
        Iterator<Element> it = root.elementIterator();
        while(it.hasNext()){
            
            Element e = it.next();
            //获取id属性(attribute是属性的意思)
            Attribute id = e.attribute("id");
            System.out.println(id.getName()+" = "+id.getStringValue());
            Element author = e.element("author");
            Element money = e.element("price");
            Element time = e.element("time");
            System.out.println(author.getName()+" = "+author.getStringValue());
            System.out.println(money.getName()+" = "+money.getData());
            System.out.println(time.getName()+" = "+time.getText());
            System.out.println("---------------------------------------------------------------");
        }
    }

}

 

 

运行结果:

  

posted @ 2019-10-06 16:59  浅滩浅  阅读(17090)  评论(1编辑  收藏  举报