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