日期:2014-05-19 浏览次数:20733 次
public static void main(String a[]) { SAXReader reader = new SAXReader(); File file = new File("E:\\tmp\\test\\test.xml"); String path = "E:\\tmp\\test"; int max = 1000; int fileNum = 0; if (!new File(path).isDirectory()) { new File(path).mkdirs(); } try { Document document = reader.read(file); List<Element> infos = document.selectNodes("catalog/info"); Document document1 = DocumentHelper.createDocument(); fileNum = (infos.size() / max) + 1; for (int i = 0; i < fileNum; i++) { new File(path + File.separator + (i + 1) + ".xml") .createNewFile(); List<Element> list = infos.subList(0, fileNum); for (int j = 0; j < list.size(); j++) { document1.setRootElement(document.getRootElement());//这个地方怎么写? document1.add((Element)list.get(j).clone()); } OutputFormat format = new OutputFormat(); format = OutputFormat.createPrettyPrint(); XMLWriter output = null; output = new XMLWriter(new FileOutputStream(new File( "E:\\tmp\\test" + i + ".xml")), format); output.write(document1); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); } }
<?xml version="1.0" encoding="UTF-8"?> <catalog> <info name="中国建筑第八工程局有限公司"> <name>中国建筑第八工程局有限公司</name> <url>http://www.cscec8b.com.cn/</url> <hangye>房地产</hangye> <address>上海市浦东新区世纪大道1568号</address> <guim>大型(1000人以上)</guim> <photo>www.fenzhi.com/image/l152393.gif</photo> <jianjie>jianjie</jianjie> </info> <info name="中铁六局"> <name>中铁六局</name> <url>http://www.crsg.com.cn/</url> <hangye>房地产</hangye> <address>北京</address> <guim>大型(1000人以上)</guim> <photo></photo> <jianjie/> </info></catalog>
/** * 保存xml * @param doc xml document对象 * @param idx 保存的文件索引号 * @throws Exception */ public static void saveXML(Document doc, int idx) throws Exception{ OutputFormat format = new OutputFormat(); format = OutputFormat.createPrettyPrint(); XMLWriter output = null; output = new XMLWriter(new FileOutputStream(new File( "c:\\" + idx + ".xml")), format); output.write(doc); output.flush(); output.close(); } public static void main(String[] args) throws Exception{ SAXReader reader = new SAXReader(); Document doc = reader.read(new File("c:/tmp.xml")); List<Element> infos = doc.selectNodes("catalog/info"); int nodeNum = infos.size(); //总共的info元素个数 int max = 1000;