DomParseService

package org.tips.dao.config;

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/***
 * 读取sql
 * @author tips
 *select uername,pwd from tips_user where uername=#uername#
 */
public class DomParseService {
	private static String CONFIG_PATH = "";

	public static String getSQL(String id) throws ParserConfigurationException,
			SAXException, IOException {
		CONFIG_PATH = TipsDBConfigListener.getPath();
		String sql = "";
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(DomParseService.class
				.getClassLoader().getResourceAsStream(CONFIG_PATH));

		Element element = document.getDocumentElement();

		NodeList sqlNodes = element.getElementsByTagName("entity");

		for (int i = 0; i < sqlNodes.getLength(); i++) {
			Element sqlElement = (Element) sqlNodes.item(i);
			if (sqlElement.getAttribute("id").equalsIgnoreCase(id)) {
				NodeList childNodes = sqlElement.getChildNodes();
				for (int j = 0; j < childNodes.getLength(); j++) {
					if (childNodes.item(j).getNodeType() != 1)
						continue;
					if (childNodes.item(j).getNodeName()
							.equalsIgnoreCase("sql")) {
						sql = childNodes.item(j).getFirstChild().getNodeValue();
					} else {
						sql = "";
					}

				}

			}

		}

		return sql.trim();
	}
}

你可能感兴趣的:(DomParseService)