3.使用dom4j修改xml文件
(1)获取xml文件封装为Document对象document,使用document.selectNodes()方法获取节点或属性信息列表。遍历列表获取节点或属性信息,进行修改,关键代码如下:
list=document.selectNodes("/trees/tree/@name");
Iterator iterator=list.iterator();
while (iterator.hasNext()) {
Attribute attribute = (Attribute) iterator.next();
if(attribute.getValue().equals("dongdongming"));
//找到dongdongming属性
attribute.setValue(“xiaoming”); //改为xiaoming
}
}catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}
list=document.selectNodes("/trees/flower"); //找到flower节点
Iterator iterator=list.iterator();
while (iterator.hasNext()) {
Element flower = (Element) iterator.next();
flower.setText("lily"); //设置节点内容
Element date=flower.addElement("date");//添加子节点
date.setText("2009-4-10");
date.addAttribute("type","calendar");//为子节点添加属性
}
try {
XMLWriter xmlWriter=new XMLWriter(new FileWriter(new File(fileName)));
xmlWriter.write(document);
xmlWriter.close();
returnValue=true;
} catch (Exception e) {
// TODO: handle exception
}
return returnValue;
}
(1)获取xml文件封装为Document对象document,使用document.selectNodes()方法获取节点或属性信息列表。遍历列表获取节点或属性信息,进行修改,关键代码如下:
list=document.selectNodes("/trees/tree/@name");
Iterator iterator=list.iterator();
while (iterator.hasNext()) {
Attribute attribute = (Attribute) iterator.next();
if(attribute.getValue().equals("dongdongming"));
//找到dongdongming属性
attribute.setValue(“xiaoming”); //改为xiaoming
}
}catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}
list=document.selectNodes("/trees/flower"); //找到flower节点
Iterator iterator=list.iterator();
while (iterator.hasNext()) {
Element flower = (Element) iterator.next();
flower.setText("lily"); //设置节点内容
Element date=flower.addElement("date");//添加子节点
date.setText("2009-4-10");
date.addAttribute("type","calendar");//为子节点添加属性
}
try {
XMLWriter xmlWriter=new XMLWriter(new FileWriter(new File(fileName)));
xmlWriter.write(document);
xmlWriter.close();
returnValue=true;
} catch (Exception e) {
// TODO: handle exception
}
return returnValue;
}