首页 > 代码库 > 通过java代码生成XML格式文件
通过java代码生成XML格式文件
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* 本类测试生成XML格式的文件
* @author guanshun
*
*/
public class CreateXMLFile {
Book[] books = new Book[]
{
new Book("1","唐诗三百首"),
new Book("2","Think in Java"),
new Book("3","神雕侠侣"),
new Book("4","葵花宝典")
};
public static void main(String[] args) throws FileNotFoundException {
CreateXMLFile createXMLFile = new CreateXMLFile();
createXMLFile.BuildXMLDoc();
}
public void BuildXMLDoc() throws FileNotFoundException {
Document dom = DocumentHelper.createDocument();
Element root=dom.addElement("books");//添加根元素
root.addAttribute("count", "4");
// root.setText("Xval标签中间的值");
for (int i = 0; i < books.length; i++) {
Element elements = root.addElement("book");
elements.setText("111111");
// elements.addAttribute("id", books[i].getId());
// elements.addAttribute("name", books[i].getName());
}
String xml=dom.asXML();
System.out.println(xml);
File f=new File("c:/XML/guanshun.xml");
PrintWriter pw=new PrintWriter(f);
pw.write(xml);
pw.close();
JOptionPane.showMessageDialog(null, "已生成xml文件,路径为为d:/xml.xml");
}
}
本文出自 “梦不落” 博客,请务必保留此出处http://5029900.blog.51cto.com/5019900/1605396
通过java代码生成XML格式文件