athrunwang

纪元
数据加载中……
dom4j对xml文件进行更新操作

dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件,可以在SourceForge上找到它 地址。如今你可以看到越来越多的Java软件都在使用dom4j来读写XML,特别值得一提的是连Sun的JAXM也在用dom4j。这是必须使用的jar包, Hibernate用它来读写配置文件。

今天项目需要对已存在的xml文件进行更新,对比之下,感觉dom4j还是比较适合的,现在将代码贴上,方便以后参考

/**
* 将订单信息写入xml文件
*
@param map
*
@throws DocumentException
*
@throws IOException
*/
public void writeXML(Map map) throws DocumentException, IOException{

if(map != null && map.get("respCode").equals("0000")){//订单提交成功,未付款
//将订单信息写入文件
File inputXML=new File("e:/orderList.xml");
//使用 SAXReader 解析 XML 文档 orderList.xml
SAXReader saxReader=new SAXReader();
Document document=saxReader.read(inputXML);

Element orders=document.getRootElement();//根节点

Element order = orders.addElement("order");//订单节点

Element merchantId = order.addElement("merchantId");//商户ID
merchantId.setText(map.get("merchantId").toString());

Element transType = order.addElement("transType");//订单状态
transType.setText(map.get("transType") == null ? "00":map.get("transType").toString());

Element merchantOrderId = order.addElement("merchantOrderId");//订单ID
merchantOrderId.setText(map.get("merchantOrderId").toString());

Element merchantOrderTime = order.addElement("merchantOrderTime");//订单时间
merchantOrderTime.setText(map.get("merchantOrderTime").toString());

Element merchantOrderAmt = order.addElement("merchantOrderAmt");//订单金额
merchantOrderAmt.setText(map.get("merchantOrderAmt").toString());


Writer writer = new FileWriter(inputXML);
OutputFormat format= OutputFormat.createPrettyPrint();//格式化
XMLWriter xmlWriter = new XMLWriter(writer,format);
xmlWriter.write(document);
xmlWriter.close();
}
}

posted on 2011-12-06 10:34 AthrunWang 阅读(172) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: