用Dom4j解析XML文件

用Dom4j解析XML文件的简单实例。
package com.dom4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 用Dom4j解析XML文件,进行简单操作
 * 
 * @author johnston678
 * @version 2009-12-09
 */
public class Dom4jParseXML {

	/**
	 * 建立一个XML文档,文档名由输入属性决定
	 * 
	 * @param filename
	 *            需建立的文件名
	 * @return 返回操作结果:0表示失败;1表示成功
	 */
	public int createXMLFile(String fileName) {
		// 返回操作结果:0表示失败;1表示成功
		int returnValue = 0;
		// 建立document对象
		Document document = DocumentHelper.createDocument();
		// 建立XML文档的根节点books
		Element booksElement = document.addElement("books");
		// 添加一行注释
		booksElement.addComment("This is a test for dom4j,holen,2009-12-09");
		// 添加第一个book节点
		Element bookElement = booksElement.addElement("book");
		// 添加show属性内容
		bookElement.addAttribute("show", "yes");
		// 添加title节点
		Element titleElement = bookElement.addElement("title");
		// 添加title节点内容
		titleElement.setText("Dom4j Tutorials");

		// 类似完成两个book节点的添加
		bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "yes");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Lucene Studing");
		bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "no");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Lucene in Action");
		
		// 添加owner节点
		Element ownerElement = booksElement.addElement("owner");
		ownerElement.setText("O'Reilly");

		// 将document中内容写入文件
		try {
			//FileWriter对象创建XMLWriter
			XMLWriter xmlWriter = new XMLWriter(new FileWriter(new File(fileName)));
			xmlWriter.write(document);
			xmlWriter.close();
			returnValue = 1;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return returnValue;
	}

	/**
	 * 修改XML文件中内容,并另存为一个新文件 重点掌握dom4j中如何添加节点,修改节点,删除节点
	 * 
	 * @param fileName
	 *            源文件
	 * @param newFileName
	 *            修改后的文件
	 * @return 返回操作结果:0表示失败;1表示成功
	 */
	public int modifyXMLFile(String fileName, String newFileName) {
		int returnValue = 0;
		try {
			// 获取document对象
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new File(fileName));

			// 如果book节点中show属性的内容为yes,则修改为no。先用xpath查找对象
			List list = document.selectNodes("/books/book/@show");
			Iterator it = list.iterator();
			while (it.hasNext()) {
				Attribute att = (Attribute) it.next();
				if (att.getValue().equals("yes")) {
					att.setValue("no");
				}
			}

			// 把owner内容改为Tshinghua
			// 并在owner节点中加入date节点,date节点的内容为2009-12-09,还为date节点添加一个属性type
			list = document.selectNodes("/books/owner");
			it = list.iterator();
			if (it.hasNext()) {
				Element ownerElement = (Element) it.next();
				ownerElement.setText("Tshinghua");
				Element dateElement = ownerElement.addElement("date");
				dateElement.setText("2009-12-09");
				dateElement.addAttribute("type", "Gregorian Calendar");

			}

			// 若title内容为Dom4j Tutorials,则删除该节点
			list = document.selectNodes("/books/book");
			it = list.iterator();
			while (it.hasNext()) {
				Element bookElement = (Element) it.next();
				Iterator iterator = bookElement.elementIterator("title");
				while (iterator.hasNext()) {
					Element titleElement = (Element) iterator.next();
					if (titleElement.getText().equals("Dom4j Tutorials")) {
						bookElement.remove(titleElement);
					}
				}
			}
			try {
				// 将document写入文件
				XMLWriter xmlWriter = new XMLWriter(new FileWriter(new File(
						newFileName)));
				xmlWriter.write(document);
				xmlWriter.close();
				returnValue = 1;
			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return returnValue;
	}

	/**
	 * 格式化XML文档,并解决中文问题
	 * @param fileName 源xml文件
	 * @param formatFileName 格式化后的文件
	 * @return 返回操作结果:0表示失败;1表示成功
	 */
	public int formatXMLFile(String fileName,String formatFileName) {
		int returnValue = 0;
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new File(fileName));
			XMLWriter xmlWriter = null;
			//格式化输出,类型IE浏览一样
			OutputFormat format = OutputFormat.createPrettyPrint();
			//指定XML编码
			format.setEncoding("gb2312");
			xmlWriter = new XMLWriter(new FileWriter(new File(formatFileName)),format);
			xmlWriter.write(document);
			xmlWriter.close();
			
			returnValue = 1;
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return returnValue;
	}
	
	/**
	 * 建立一个XML文档,文档名由输入fileName决定,字符编码由encoding指定,用来创建中文节点,并格式化输出
	 * @param fileName XML文件名
	 * @param encoding 文件编码
	 * @return 返回操作结果:0表示失败;1表示成功
	 */
	public int createEncodingXMLFile(String fileName,String encoding){
		int returnValue = 0;
		Document document = DocumentHelper.createDocument();
		Element books = document.addElement("books");
		
		Element book = books.addElement("book");
		Element bookname = book.addElement("bookname");
		bookname.setText("Java编程思想");
		
		book = books.addElement("book");
		bookname = book.addElement("bookname");
		bookname.setText("XML基础教程");
		

		try {
			//格式化输出,类型IE浏览一样
			OutputFormat format = OutputFormat.createPrettyPrint();
			//指定XML编码
			format.setEncoding(encoding);
			//FileOutputStream对象创建XMLWriter
			XMLWriter writer = new XMLWriter(new FileOutputStream(fileName),format);
			writer.write(document);
			writer.close();
			returnValue = 1;
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return returnValue;
	}
	public static void main(String[] args) {
		Dom4jParseXML dom4j = new Dom4jParseXML();
		dom4j.createXMLFile("src/com/xmlfile/holen.xml");
		dom4j.modifyXMLFile("src/com/xmlfile/holen.xml",
				"src/com/xmlfile/modifyholen.xml");
		dom4j.formatXMLFile("src/com/xmlfile/modifyholen.xml","src/com/xmlfile/formatmodifyholen.xml");
		dom4j.createEncodingXMLFile("src/com/xmlfile/books.xml", "gb2312");
	}

}

你可能感兴趣的:(编程,xml,IE,Lucene)