XMLUtil.java 4.8 KB
/*
 * Created on 2006-3-30
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.sitech.util;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

/**
 * @author Administrator
 * 
 * XML工具类
 * 
 * DocumentBuilderFactory 和 DocumentBuilder is NOT guaranteed to be thread safe.
 * 所以每个方法中都是新创建
 */
public class XMLUtil {

	/**
	 * Normalizes the given string. 在向xml文件中写入东西时,一些特殊字符需要处理 不过如果使用 <![CDATA[]]>
	 * 的话,可以不处理
	 */
	public static String normalize(String s) {
		StringBuffer str = new StringBuffer();

		int len = (s != null) ? s.length() : 0;
		for (int i = 0; i < len; i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '<': {
				str.append("&lt;");
				break;
			}
			case '>': {
				str.append("&gt;");
				break;
			}
			case '&': {
				str.append("&amp;");
				break;
			}
			case '"': {
				str.append("&quot;");
				break;
			}
			/*
			 * case '\r': case '\n': { str.append("&#");
			 * str.append(Integer.toString(ch)); str.append(';'); break; }
			 */
			default: {
				str.append(ch);
			}
			}
		}
		return str.toString();
	}

	/**
	 * 解析一个xml文件,返回其Document filename为绝对路径
	 */
	public static Document parseFile2Doc(String filename) {
		Document doc = null;

		try {

			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

			doc = docBuilder.parse(filename);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		return doc;
	}// end parseFile2Doc(String filename)

	/**
	 * 解析一个String格式的xml数据,返回其Document
	 */
	public static Document parseString2Doc(String content) {
		Document doc = null;

		try {

			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

			doc = docBuilder.parse(new java.io.ByteArrayInputStream(content
					.getBytes()));

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		return doc;
	}// end parseString2Doc(String filename)

	/**
	 * 创建一个新xml document
	 */
	public static Document newDocument() {
		Document doc = null;

		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

			doc = docBuilder.newDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		return doc;
	}// end Document newDocument()

	/**
	 * 将document写入到文件中 filename为绝对路径
	 */
	public static void writeXmlFile(Document doc, String filename) {

		try {
			// Prepare the DOM document for writing
			Source source = new DOMSource(doc);

			// Prepare the output file
			File file = new File(filename);
			Result result = new StreamResult(file);

			// Write the DOM document to the file
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			xformer.transform(source, result);

		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}

	}// end writeXmlFile(Document doc, String filename)

	/**
	 * Creates ElementNode for given tag with particular text as content.
	 */
	public static Element createTextNode(Document doc, String tag,
			String content) throws ParserConfigurationException {

		Element node = doc.createElement(tag);
		Text t = doc.createTextNode(content);
		node.appendChild(t);

		return node;
	}

	/**
	 * Creates ElementNode for given tag with particular text as content.
	 */
	public static Element createCDATATextNode(Document doc, String tag,
			String content) throws ParserConfigurationException {

		Element node = doc.createElement(tag);
		Text t = doc.createCDATASection(content);
		node.appendChild(t);

		return node;
	}
}

// XmlUtil
// ////////////////// end of file ////////////////////