import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Updatel {
private void doCycXml(Element element,List delList) {
if (element == null)
return;
Iterator iter = element.elementIterator();
Element temp = null;
while (iter.hasNext()) {
temp = (Element)iter.next();
Attribute att = temp.attribute("name");
if (att != null)
for (int i = 0; i < delList.size(); i++) {
if (att.getValue().equals((String)delList.get(i))) {
temp.getParent().remove(temp);
delList.remove(i);
break;
}
}
if (!element.elementIterator().hasNext()) {
element.getParent().remove(element);
}
if (delList.size()==0) return;
doCycXml(temp,delList);
}
}
public void updateXml(String sourceXml,String updateFile,String destXml) throws Exception {
FileInputStream fis = new FileInputStream(updateFile);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
List delList = new ArrayList();
String str = null;
while ((str = br.readLine()) != null) {
delList.add(str);
}
//如果没有要删除的
if (delList.size() == 0) return;
SAXReader reader = new SAXReader();
//声明文档对象
Document doc = null;
//读取XML文档
doc = reader.read(new File(sourceXml));
//声明跟元素
Element root = doc.getRootElement();
doCycXml(root,delList);
fis.close();
XMLWriter writer = null;
OutputFormat format = OutputFormat.createPrettyPrint();
// 格式编码为“utf-8”
format.setEncoding("utf-8");
writer = new XMLWriter(new FileOutputStream(new File(destXml)), format);
writer.write(doc);// 写XML文档
writer.close();// 关闭输出流
}
public static void main(String args[]) throws Exception {
Update u = new Updatel();
u.updateXml("×××", "×××", "×××");
}
}
</script>