当前位置: 代码迷 >> 综合 >> 解析XML(3/4)——JDOM(1/2)----将数据从XML文件中读取
  详细解决方案

解析XML(3/4)——JDOM(1/2)----将数据从XML文件中读取

热度:75   发布时间:2023-11-07 13:21:02.0

一、books.xml

<?xml version="1.0" encoding="UTF-8"?>
<bookstore><book id="1"><name>冰与火之歌</name><author>乔治马丁</author><year>2014</year><price>88</price></book><book><id>2</id><name>安徒生童话</name><author>丹麦</author><year>2004</year><price>66</price></book><book id="3" name="ha "><id><a>即使他---*</a>3</id><name>java开发</name><author>美国</author><year>2000</year><price>99</price></book>
</bookstore>

二、JDOMTest.java

package com.test.jdomtest;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;public class JDOMTest {public static void main(String[] args) {// 准备对books.xml文件的JDOM解析// 准备工作// 1、创建SAXBuilder的对象SAXBuilder saxBuilder = new SAXBuilder();FileInputStream in;try {// 2、创建输入流,将XML文件加载到输入流中in = new FileInputStream("books.xml");//InputStreamReader isr = new InputStreamReader(in, "utf-8");// 3、通过saxBuilder的build()方法,将输入流加载到saxBuilder中Document document = saxBuilder.build(in);//Document document = saxBuilder.build(isr);// 4、通过document对象获取XML文件的根节点Element rootElement = document.getRootElement();// 5、获取根节点下的子节点的集合List<Element> bookList = rootElement.getChildren();// 继续进行解析for (Element book : bookList) {System.out.println("========开始解析第" + (bookList.indexOf(book) + 1) + "本书========");//解析book属性集合List<Attribute> attrList = book.getAttributes();
/*				//知道节点下属性名,获取节点值String va = book.getAttributeValue("id");System.out.println("********他的ID是:" + va);*/for (Attribute attribute : attrList) {//获取属性名String name = attribute.getName();//获取属性值String value = attribute.getValue();System.out.println("!!!!!属性名是:" + name + "---属性值是:" + value);}//遍历book节点的子节点的名+值List<Element> bookChilds = book.getChildren();for (Element child : bookChilds) {System.out.println("/节点名:" + child.getName() + "节点值:" + child.getValue());}System.out.println("--------结束解析第" + (bookList.indexOf(book) + 1) + "本书--------");}} catch (FileNotFoundException e) {e.printStackTrace();} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

三、解析时乱码处理

1、修改XML文件中encoding编码集
2、在有IO的代码中添加:InputStreamReader isr = new InputStreamReader(in, "utf-8");
  相关解决方案