需要的jar:jdom-2.0.5.jar
package com.zhang.xml.jdom; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; public class JDomParser { public static void main(String[] args) throws Exception { SAXBuilder builder = new SAXBuilder(); InputStream in = new FileInputStream("books.xml"); InputStreamReader isr = new InputStreamReader(in, "UTF-8");//解决乱码 Document document = builder.build(isr); Element element = document.getRootElement(); List<Element> books = element.getChildren(); for(Element book : books) { System.out.println("------开始解析第" + (books.indexOf(book) + 1) + "本书------"); List<Attribute> attrs = book.getAttributes(); for(Attribute attr : attrs) { System.out.println("---属性名:" + attr.getName() + "-->属性值:" + attr.getValue() + "---"); } List<Element> eles = book.getChildren(); for(Element ele : eles) { System.out.println("---子节点:" + ele.getName() + "-->节点值:" + ele.getValue()); } System.out.println("------结束解析第" + (books.indexOf(book) + 1) + "本书------"); System.out.println(); } } }
结果: