jdom对xml文件的读写操作
1. 读取XML文件Java源代码:
1) xml文件:
<?xml version="1.0" encoding="gb2312"?>
<messages>
<message id="1">
<title>软件工程师</title>
<content>
<name>solidwang</name>
<age>23</age>
</content>
<email>wzzcctv@126.com</email>
</message>
<message id="2">
<title>导游</title>
<content>
<name>eillenwang</name>
<age>20</age>
</content>
<email>eillenwang@163.com</email>
</message>
</messages>
2) 读取xml文件的Java源代码:
package com.solid.xml;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class ReadXML {
public static void main(String[] args) throws FileNotFoundException, JDOMException {
//创建构造器
SAXBuilder sb = new SAXBuilder();
//读入指定文件
Document doc = sb.build(new FileInputStream("WebRoot/xmlFile/test.xml"));
//获得根节点
Element root = doc.getRootElement();
//将根节点下所有子节点放入到list中
List list = root.getChildren();
for(int i=0; i<list.size(); i++) {
System.out.println("======================");
//取得节点实例
Element item = (Element)list.get(i);
//取得属性值
String id = item.getAttribute("id").getValue();
System.out.println("id-->" + id);
//取得子节点的值
String sub1 = item.getChild("title").getText();
System.out.println("sub1-->" + sub1);
//取得子节点的子节点的值
if(item.getChild("content").getChildren().size() > 0) {
String sub21 = item.getChild("content").getChild("name").getText();
String sub22 = item.getChild("content").getChild("age").getText();
System.out.println("sub21-->" + sub21);
System.out.println("sub22-->" + sub22);
}
//取得子节点
String sub3 = item.getChild("email").getText();
System.out.println("sub3-->" + sub3);
}
}
}
2. 写XML文件Java源代码:
package com.solid.xml;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public class WriteXML {
public static void BuildXMLDoc() throws FileNotFoundException, IOException {
//创建根节点list
Element root = new Element("list");
//将根节点添加到文档中
Document doc = new Document(root);
//循环创建(也可以遍历数据库表取得结果集)
for(int i=0; i<5; i++) {
//创建节点company
Element elements = new Element("company");
//为company节点添加属性id
elements.addAttribute("id", ""+i);
//给company节点添加子节点并赋值
//new Element("company_name")中的 "company_name" 替换成表中相应字段,setText("name")中 "name 替换成表中记录值;
elements.addContent(new Element("company_name").setText("name" + i));
elements.addContent(new Element("company_email").setText("@" + i+ ".com"));
//为父节点list添加company子节点
root.addContent(elements);
}
//输出xml文件
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.output(doc, new FileOutputStream("WebRoot/xmlFile/company_list.xml"));
}
public static void main(String[] args) {
try {
System.out.println("===start===");
WriteXML.BuildXMLDoc();
System.out.println("===end===");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}