使用dom4j做简单的xml操作

/**
 * @author zymaxs
 *
 */


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlTool {
	private SAXReader reader = new SAXReader();
	private InputStream in = null;
	private Document doc = null;
	private Element root = null;

	public XmlTool(String path) {
		try {
			in = new FileInputStream(new File(path));
			doc = reader.read(in);
			root = doc.getRootElement();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void updateElementValue(String element, String value) {
		String[] path = element.split("//");
		Element n = root;
		try {
			for (String s : path) {
				n = n.element(s);
			}
			n.setText(value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void deleteElement(String element) {
		String[] path = element.split("//");
		Element n = root;
		try {
			for (String s : path) {
				n = n.element(s);
			}
			n.getParent().remove(n);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getElementValue(String element) {
		String[] path = element.split("//");
		Element n = root;
		String text = "";
		try {
			for (String s : path) {
				n = n.element(s);
			}
			text = n.getText();
		} catch (Exception e) {
			//e.printStackTrace();
			return null;
		}

		return text;
	}

	public void addElement(String element, String Value) {
		String[] path = element.split("//");
		Element n = root;
		for (String s : path) {

			if (null != n.element(s)) {
				n = n.element(s);
			} else {
				n.addElement(s);
				n = n.element(s);
			}
		}
		n.setText(Value);
	}

	public String getXML() {
		return root.asXML();
	}
}


posted @ 2014-01-07 09:50  zymaxs  阅读(101)  评论(0编辑  收藏  举报