首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

札记 -XML解析<三>

2012-12-21 
笔记 ------XML解析三JDom 解析:使用简单package jdomimport java.io.Fileimport java.io.FileNotFoun

笔记 ------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();}}}
?

热点排行