服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

使用jdom操作xml系列文章三 平面式xml文件转层叠式xml文件


  使用jdom操作xml系列文章三 平面式xml文件转层叠式xml文件
package jing.xml;
/**
* <p>title: 平面式xml文件转层叠式xml文件</p>
* <p>description: </p>
* <p>copyright: copyright (c) 2004</p>
* <p>company: </p>
* @author 欧朝敬 13873195792
* @version 1.0
*/
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import org.jdom.xpath.*;
import java.io.*;
import java.util.*;

public class xmltotree {
public saxbuilder sb = null;
public document doc = null;
public element root = null;
public xmltotree() throws exception {
sb = new saxbuilder(); // 新建立构造器
doc = sb.build(new fileinputstream("company.xml")); // 读入文件
root = doc.getrootelement(); // 获得根元素element

}

public void listelemnet(string pid, element element) throws exception {
list find = xpath.selectnodes(root, "/root/row[@pid=´" + pid + "´]");
int rowcount = find.size();
for (int i = 0; i < rowcount; i++) {
element findelement = (element) find.get(i);
element element0 = new element("row");
list attrib = findelement.getattributes();
int j = attrib.size();
for (int h = 0; h < j; h++) {
attribute attribute = (attribute) attrib.get(h);
element0.setattribute(
attribute.getname(),
attribute.getvalue());

}
element.addcontent(element0);
listelemnet(findelement.getattributevalue("cid"), element0);
}
}

public static void main(string[] args) throws exception {
xmltotree bb = new xmltotree();

element roote = new element("root");
document tdocument = new document(roote); //创建文档root元素

bb.listelemnet("0", roote);

xmloutputter outp = new xmloutputter(format.getprettyformat()); //格式华输出,产生缩进和换行
format format = outp.getformat();
format.setencoding("gb2312"); //设置语言
format.setexpandemptyelements(true); //设置输出空元素为<sample></sample>格式
outp.setformat(format);
outp.output(tdocument, new fileoutputstream("companytree.xml")); //输出xml文档
//outp.output(tdocument,system.out);
system.out.print("xml 文档生成完毕!");
}
}

扫描关注微信公众号