import java.io.*;import java.util.*;import org.jdom.*;import org.jdom.output.*;public classXmlCreate {public static classAutoXML {private List fruit = new ArrayList();//初始化即将显示的在xml中的元素...
public voidinitList(){
fruit.add("草莓");
fruit.add("橘子");
fruit.add("香蕉");
fruit.add("葡萄");
}public voidBuildXML(){
initList();//创建根节点...
Element root = new Element("水果");//将根节点添加到文档中...
Document Doc = newDocument(root);for(int i = 0; i < fruit.size(); i++){//创建各种类水果的节点...
Element elements = newElement(fruit.get(i));//给各种水果节点加子节点...比如价格...
elements.addContent(new Element("价格").setText(i*10+"元"));
root.addContent(elements);
XMLOutputter XMLOut= newXMLOutputter(FormatXML());try{
String fileName="fruit.xml";
File file= new File("D:\\",fileName);if(!file.exists()){
file.createNewFile();
}
XMLOut.output(Doc,new FileOutputStream("D:\\fruit.xml"));
}catch(FileNotFoundException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}publicFormat FormatXML(){//格式化生成的xml文件,如果不进行格式化的话,生成的xml文件将会是很长的一行...
Format format =Format.getCompactFormat();
format.setEncoding("utf-8");
format.setIndent(" ");returnformat;
}public static voidmain(String[] args){try{
AutoXML mXml= newAutoXML();
System.out.println("生成xml文件.....");
mXml.BuildXML();
}catch(Exception e){
e.printStackTrace();
}
}
}
}