笔记 ------XML解析<三>

JDom 解析:使用简单

package jdom;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

public class JDOMParser {

	public static void main(String[] args) {
		SAXBuilder build = new SAXBuilder();
		String path = JDOMParser.class.getClassLoader().getResource("books.xml").getPath();
		try {
			//获得文档对象
			Document doc = build.build(path);
			//获得根节点
			Element root = doc.getRootElement();
			//根据XPath获得单个元素或多个元素
			List<Element> list = XPath.selectNodes(root, "//book-list/book");
			for(int i= 0; i < list.size(); i++){
				Element ele = list.get(i);
				System.out.print(ele.getAttributeValue("id")+"\t");
				System.out.print(ele.getChildText("name")+"\t");
				System.out.print(ele.getChildText("author")+"\t");
				System.out.println(ele.getChildText("price")+"\t");
			}
			
			createElement(root, doc, path);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}
	
	private  static void createElement(Element root, Document doc, String path){
		Element book = new Element("book");
		book.setAttribute(new Attribute("id", "f"));
		
		Element name = new Element("name");
		name.addContent("数据结构");
		
		Element author = new Element("author");
		name.addContent("严蔚敏");
		
		Element price = new Element("price");
		name.addContent("25");
		
		book.addContent(name);
		book.addContent(author);
		book.addContent(price);
		
		root.addContent(book);
		
		XMLOutputter out = new XMLOutputter();
		//设置编码
		//out.setFormat(Format.getCompactFormat().setEncoding("GBK"));
		//以字符串形式输出
		String str = out.outputString(doc);
		System.out.println(str);
		
		System.out.println(path);
		//写入文件
		try {
			out.output(doc, new FileOutputStream(new File(path)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值