六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 13|回复: 0

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

[复制链接]

升级  94%

11

主题

11

主题

11

主题

童生

Rank: 1

积分
47
 楼主| 发表于 2013-2-3 10:40:43 | 显示全部楼层 |阅读模式
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();}}}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表