您的位置:首页 > 编程语言 > Java开发

java通过dom4j创建xml文件

2012-06-11 15:13 281 查看
/**

* @param foldPath 各个子文件夹的xml的存放位置

* @param xmlPath 总xml创建后的存放位置

*/

public static void createDescriptionXML(String[] foldPath,String xmlPath){

Document document= DocumentHelper.createDocument();

Element root=document.addElement("polaroids");

root.addElement("color").setText("0x0099CC");

root.addElement("title").setText("description");

root.addElement("music").setText("music.mp3");

root.addElement("contact").setText("contact@contact.com");

root.addElement("galleries").setText("INFCN");

Element ele=root.addElement("galleries");

int p=0;

for(int i=0;i<foldPath.length;i++){

p=p+1;

ele.addElement("gallery").addAttribute("dir", foldPath[i]).setText("fold"+p);

}

doc2Xml(document,xmlPath);

}





//将document写入的xml文件

public static int doc2Xml(Document doc,String xmlPath){

OutputFormat format=OutputFormat.createPrettyPrint();

format.setEncoding("UTF-8");

XMLWriter xmlWriter=null;

File file=new File(xmlPath);

int flag=0;

try {

if(!file.getParentFile().exists()){//目标文件夹不存在

file.getParentFile().mkdirs();

}

xmlWriter=new XMLWriter(new FileWriter(file),format);

xmlWriter.write(doc);



} catch (IOException e) {

// TODO Auto-generated catch block

flag=1;

e.printStackTrace();

}finally{

if(xmlWriter!=null){

try {

xmlWriter.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

return flag;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: