通过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("---------------------------------------------------------------");
        }
    }

}

 

 

运行结果:

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM