由于项目需要,需要写一棵树来展示业务种类信息,网上找了诸多的代码,基本没几个可以直接拿来用的,自己琢磨了几天,把这事搞定了,发一篇文章上来,给需要朋友,以后有需要,直接来这儿看看代码,复制到本地直接使用即可,其中有些属性之类的值方面的代码进行了简化,但不影响具体的使用,有需要的朋友直接扩展节点的属性即可。
开发环境:eclipse,spring+ibatis
业务需求:生成一颗组织结构树
public class TransListToXML {
/**
* 生成document
*
* @return document
* */
public static Document generateXML() {
// 获取根部门
Organization rootOrg = getRootOrg();
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
Element orgRoot = root.addElement(rootOrg.getName());
appendXML(orgRoot, rootOrg.getId());
return doc;
}
/**
* 获取根节点下直属部门拼接XML 使用递归,一级一级往下查
* */
public static void appendXML(Element e, String orgId) {
List<Organization> orgList = getOrgByParentId(orgId);
for (Organization org : orgList) {
Element e1 = e.addElement(org.getName());
appendXML(e1, org.getId());
}
}
/**
* 获取父节点下所有的子节点
* */
public static List<Organization> getOrgByParentId(String orgId) {
String configLocation = "applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(
configLocation);
OrganizationService orgSer = (OrganizationService) context
.getBean("organizationService");
return orgSer.getOrgByParentId(orgId);
}
/**
* 获取部门根节点
*
* @return Organization
* */
public static Organization getRootOrg() {
String configLocation = "applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(
configLocation);
OrganizationService orgSer = (OrganizationService) context
.getBean("organizationService");
Organization rootOrg = orgSer.getRootOrg();
return rootOrg;
}
/**
* 写入XMl文件
*
* @param document
* 所要写入的文件内容
* @param outFile
* 文件存放的地址
* */
public static void writeDocument(Document docment, String outFile) {
try {
FileOutputStream fileWriter = new FileOutputStream(outFile);// 读取文件
OutputFormat xmlFormat = OutputFormat.createPrettyPrint();// 设置文件格式
xmlFormat.setEncoding("utf-8");
XMLWriter xmlWriter = new XMLWriter(fileWriter, xmlFormat);// 创建写文件方法
xmlWriter.write(docment);// 写入文件
xmlWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("文件没有找到");
e.printStackTrace();
}
}
public static void main(String[] args) {
Document doc = TransListToXML.generateXML();
String outFile = "d://result.xml";
writeDocument(doc, outFile);
}
}
代码不做解释了,注释写的很明白。
如有不懂,欢迎进行相互交流