java-利用dom4j操作(写)xml文件
public void write(String cusxmlpath, List<String> cuslist) {
//定义写xml文件的XMLWriter
XMLWriter writer = null;
try {
//创建Document对象
Document document = DocumentHelper.createDocument();
//创建根对象 root
Element root = document.addElement(“roots”);
for (String entity : cuslist) {
//root下创建第一个xml元素student,并且给student增加属性name
Element element = root.addElement(“student”).addAttribute(
”name”, entity);
//root增加第二个元素 age,并且赋值10
element.addElement(“age”).addText(“10″);
//root增加第三个元素 sex,并且赋值f
element.addElement(“sex”).addText(“f”);
//如果你的xml需要格式化,就需要下面这些了OutputFormat OutputFormat of = new
OutputFormat(); of.setIndent(true); of.setNewlines(true);
//在通过XMLWriter写xml的时候,需要把of交给XMLWriter来做格式化xml writer = new
XMLWriter(new FileOutputStream(cusxmlpath), of); writer.write(document); }
catch (Exception e) { // TODO: handle exception e.printStackTrace(); }
finally { if (writer != null) try { //记住,在使用XMLWriter写文件一定要关闭流
writer.close(); } catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); }
}
}