import java.io.FileWriter;
import
java.io.IOException;
import
java.io.Writer;
import
java.util.Iterator;
import
java.util.List;
import
org.dom4j.Attribute;
import
org.dom4j.Document;
import
org.dom4j.DocumentException;
import
org.dom4j.DocumentHelper;
import
org.dom4j.Element;
import
org.dom4j.io.OutputFormat;
import
org.dom4j.io.SAXReader;
import
org.dom4j.io.XMLWriter;
public class Dom4JXML
{
public void
updateXML(){
try
{
//创建读入对象
SAXReader reader = new
SAXReader();
//创建document实例
Document doc = reader.read("D:\\tests.xml");
//查找节点emp下的id属性
List listAttr = doc.selectNodes("/tests/test/@id");
Iterator itAttr = listAttr.iterator();
while(itAttr.hasNext()){
Attribute attr = (Attribute)
itAttr.next();
//emp属性修改为001
attr.setValue("001");
}
//查找emp下的name节点
List listText = doc.selectNodes("/tests/test/name");
Iterator itText = listText.iterator();
while(itText.hasNext()){
Element textEle = (Element)
itText.next();
//name节点的文本内容修改为"张三"
textEle.setText("张三");
}
//查找emp节点
List listEle = doc.selectNodes("/tests/test");
Iterator itEle = listEle.iterator();
while(itEle.hasNext()){
Element empEle = (Element)
itEle.next();
//查找emp下的sex节点
Iterator itSex =
empEle.elementIterator("sex");
while(itSex.hasNext()){
Element sexEle = (Element)
itSex.next();
//删除sex节点
empEle.remove(sexEle);
}
}
//创建写出流
Writer out = new
FileWriter("D:\\tests(update).xml");
// 格式化输出
OutputFormat format = OutputFormat.createPrettyPrint();
//OutputFormat format =
OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
//创建写出对象
XMLWriter writer = new
XMLWriter(out,format);
writer.write(doc);
writer.close();
System.out.println("生成tests(update).xml成功。");
} catch
(Exception e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
publicstaticvoid
main(String[] args) {
new Dom4JXML().updateXML();
}
}
阅读(1191) | 评论(0) | 转发(0) |