日期:2014-05-19 浏览次数:20662 次
public class Dom4jxml {
//写XML文件
public void Writer() throws IOException {
Document doc = DocumentHelper.createDocument();
Element goods = doc.addElement("goods");//添加根节点
Element phone = goods.addElement("Phone");//根节点下添加Phone节点
Element good1 = phone.addElement("good");//Phone节点下添加good节点
Element brand1 = good1.addElement("品牌");
brand1.setText("三星");//设置节点值
brand1.addAttribute("hot","yes");//设置节点属性
Element price1 = good1.addElement("价格");
price1.setText("3000");
Element good2 = phone.addElement("good");
Element brand2 = good2.addElement("品牌");
brand2.setText("苹果");
brand2.addAttribute("hot","yes");
Element price2 = good2.addElement("价格");
price2.setText("4000");
Element pad = goods.addElement("Pad");
Element good3 = pad.addElement("good");
Element brand3 = good3.addElement("品牌");
brand3.setText("苹果");
brand3.addAttribute("hot","yes");
Element price3 = good3.addElement("价格");
price3.setText("4500");
FileWriter fw = new FileWriter("goods.xml");
OutputFormat format = OutputFormat.createPrettyPrint();//缩减型格式
//OutputFormat format = OutputFormat.createCompactFormat();//紧凑型格式
format.setEncoding("UTF-8");//设置编码
//format.setTrimText(false);//设置text中是否要删除其中多余的空格
XMLWriter xw = new XMLWriter(fw, format);
xw.write(doc);
xw.close();
}
//读XML文件
public void Reader() throws DocumentException {
SAXReader sr = new SAXReader();
Document doc = sr.read(new File("goods.xml"));
Element root = doc.getRootElement();//得到根节点
Element phone = root.element("Phone");//得到根节点下Phone节点
Iterator iter1 = phone.elementIterator("good");//遍历Phone节点下所有good节点
while(iter1.has