1、jdom
1.1 是什么?
1.2 用来干什么?
1.3 怎么用?
1.4 使用后感悟和小结!
1.1 Jdom 是一种java工具包,利用纯Java技术对XML文档进行解析,生成,序列化和多种操作。
1.2 Jdom 是用来快速开发xml的应用程序。
1.3 jdom的使用:
简单测试demo1:
public class Test {
public static void main(String[] args) throws FileNotFoundException,
JDOMException, IOException {
//读C盘里面的foo.xml文件的内容
readXMLFile();
//写入到C盘里面的foo2.xml文件里去
writeXMLFile();
}
private static void readXMLFile() throws FileNotFoundException,
JDOMException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new FileInputStream("c:foo.xml"));
Element root = doc.getRootElement();
List<Element> list = root.getChildren();
for (int i = 0; i < list.size(); i++) {
String name1 = list.get(i).getName();
String value1 = list.get(i).getAttributeValue("price");
System.out.println(" name1 = " + name1);
System.out.println(" value1 = " + value1);
}
}
private static void writeXMLFile() throws FileNotFoundException,
IOException {
Element root = new Element("shop");
root.setAttribute("name", "shop for geeks");
root.setAttribute("location", "Tokyo, Japan");
Element item1 = new Element("computer");
item1.setAttribute("name", "iBook");
item1.setAttribute("price", "1200$");
root.addContent(item1);
// do the similar for other elements
XMLOutputter out = new XMLOutputter();
out.output(new Document(root), new FileOutputStream("c:foo2.xml"));
}
}
1、读xml文件操作:
SAXBuilder build = new SAXBuilder();
Document doc = build.build( *);
Element root = doc.getRootElement();
Element item = root.getChild(String name);
2、写xml文件操作
Element root = new Element(*);
root.setAttribute(String name ,String value);
Element item = new Element(*);
item.setAttribut(String name,String value);
root.addContent(item);
Docment doc = new Docment();
doc.setRootElement(root);
XMLOutputter out = new XMLOutputter();
out.output(doc,new FileWrite(string filepath))
参考网址: