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

本文介绍了一种利用Java的JDOM库解析XML文件的方法,包括如何读取XML文件、解析节点及其属性,并展示了处理乱码问题的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值