java dom4j写入XML
引用的两个jar包
dom4j-1.6.1.jar
jaxen.jar
//=========================代码 import java.io.FileWriter; import java.util.List; import org.dom4j.*; import org.dom4j.io.*; public class TestDom4 { public static void main(String[] args) { Test(); } public static void Test() { String fileName = System.getProperty("user.dir")+ "\\LoaneeProduct.xml"; // 当前路径下的demo.xml try { SAXReader reader = new SAXReader(); Document doc = reader.read(fileName); // 加载xml文件 List peoples = null; Element products = null; try { products = (Element) doc.selectSingleNode("./products"); // 选择所有具有name属性的节点(即demo.xml中的所有card节点) } catch (Exception ex) { System.out.println("异常信息:" + ex); } products.addElement("product").addAttribute("type", "cp"); // .addText("第六个产品"); Element a = (Element) products .selectSingleNode("(//product)[last()]"); a.addElement("id").addAttribute("type", "3").addText("222"); a.addElement("name").addAttribute("type", "3").addText("第六个产品"); // Node node = doc.selectSingleNode("(//question)[last()]/@id"); /* * products.addElement("email").addAttribute("type", * "私人").addCDATA("private@some-domain.com"); //设置CDATA内容 */ // 将上述改动保存到文件demo2.xml FileWriter fileWriter = new FileWriter( System.getProperty("user.dir") + "\\LoaneeProduct.xml"); OutputFormat format = OutputFormat.createPrettyPrint(); // 设置美观的缩进格式,便于阅读 format.setEncoding("gb2312"); // 设置文本格式 // format = OutputFormat.createCompactFormat();//设置紧凑格式(消除多余空格),便于下载 XMLWriter writer = new XMLWriter(System.out, format); writer.setWriter(fileWriter); writer.write(doc); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
//===========================XML 结构
<?xml version="1.0" encoding="gb2312"?> <products> <product> <id>78</id> <name>悟能月付3.0</name> </product> <product> <id>220</id> <name>东方步云</name> </product> <product> <id>35</id> <name>畜牧贷</name> </product> <product> <id>176</id> <name>瑞恩传媒</name> </product> <product> <id>199</id> <name>借东风-凯琦</name> </product> <product type="cp"> <id type="3">222</id> <name type="3">第六个产品</name> </product> <product type="cp"> <id type="3">222</id> <name type="3">第六个产品</name> </product> </products>