JDOM读写XML文件示例
写文件:
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
public class JavaXML {
public void BuildXMLDoc() throws IOException, JDOMException {
// 创建根节点 list;
Element root = new Element("list");
// 根节点添加到文档中;
Document Doc = new Document(root);
// 此处 for 循环可替换成 遍历 数据库表的结果集操作;
for (int i = 0; i < 5; i++) {
// 创建节点 user;
Element elements = new Element("company");
// 给 company 节点添加属性 id;
elements.setAttribute("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);
}
XMLOutputter XMLOut = new XMLOutputter();
// 输出company_list.xml文件;
XMLOut.output(Doc, new FileOutputStream("company_list.xml"));
}
/**
* 主方法用于测试
* @param args
*/
public static void main(String[] args) {
try {
JavaXML javaXML = new JavaXML();
javaXML.BuildXMLDoc();
} catch (Exception e) {
e.printStackTrace();
}
}
}
读文件:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class ReadXML {
public List GetCompanyList(String XML_url){
try {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(XML_url);
Element root = doc.getRootElement();
List list = root.getChildren();
ArrayList formList = new ArrayList();
Iterator iter = list.iterator();
while (iter.hasNext()) {
Element e = (Element) iter.next();
CompanyListForm companyListForm = new CompanyListForm();
companyListForm.setCompany_name(e.getChildText("company_name"));
companyListForm.setCompany_email(e.getChildText("company_email"));
formList.add(companyListForm);
}
Iterator iterator = moList.iterator();
while (iterator.hasNext()) {
CompanyListForm companyListForm = (CompanyListForm) iterator.next();
System.out.println("company_name:" + companyListForm.getCompany_name());
System.out.println("company_email:" + companyListForm.getCompany_email());
}
return formList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 主方法用于测试
* @param args
*/
public static void main(String[] args) {
ReadXML readXml = new ReadXML();
readXml.GetCompanyList("e:company_list.xml");
}
}