这篇文章主要介绍了通过Java读取xml文件内容过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
需要下载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("---------------------------------------------------------------"); } } }
运行结果: