使用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()); //格式华输出,产生缩进和换行
编程大本营HTTp://www.timihome.net
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 文档生成完毕!");
}
} |
|
本页摘自URL地址: http://www.timihome.net/html/java/java_j2ee/20070625/3823.html