dom4j 解析xml

import java.io.*;
import java.util.List;

import org.dom4j.*;
import org.dom4j.io.*;

public class DomXML {

 public static String xmlPath;

 public static void deleteNode(String express) throws DocumentException,
   IOException {
  // 找到结点并删除
  SAXReader reader = new SAXReader();
  Document document = reader.read(xmlPath);
  Element element = (Element) document.selectSingleNode(express);
  if (element != null) {
   element.getParent().remove(element);
  }
  // 保存
  saveXMLFile(document);
 }

 public static void deleteChildNode(String express)
   throws DocumentException, IOException {
  // 找到结点并删除
  SAXReader reader = new SAXReader();
  Document document = reader.read(xmlPath);
  List<Element> elements = document.selectNodes(express);
  for (Element element : elements) {
   element.getParent().remove(element);
  }
  // 保存
  saveXMLFile(document);
 }

 @SuppressWarnings("deprecation")
 public static void UpdateNode(String express, String attr, String value,
   String describe) {
  try {
   SAXReader reader = new SAXReader();
   Document document = reader.read(xmlPath);
   Element element = (Element) document.selectSingleNode(express);
   element.setAttributeValue(attr, value);
   // 保存
   saveXMLFile(document);
  } catch (DocumentException e) {
   System.out.println("更新配置出错:" + describe);
   e.printStackTrace();
  }
 }

 // 添加节点
 public static void creatNode(String express, Element child)
   throws DocumentException, IOException {
  SAXReader reader = new SAXReader();
  Document document = reader.read(xmlPath);
  Element element = (Element) document.selectSingleNode(express);
  element.add(child);
  // 保存
  saveXMLFile(document);
 }

 // 保存文件
 private static void saveXMLFile(Document document) {
  try {
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding("GB2312");
   XMLWriter writer = new XMLWriter(new FileWriter(new File(xmlPath)),
     format);
   writer.write(document);
   writer.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

你可能感兴趣的:(dom4j)