本文主要是介绍使用dom4j解析指定节点下的信息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
需要的 jar 包:
dom4j-1.6.1.jar
jaxen-1.1.1.jar
log4j-1.2.8.jar
sql.xml
<?xml version="1.0" encoding="UTF-8"?> <config><sql><user><queryList>select * from t_user</queryList></user></sql> </config>
java代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;/*** @ClassName: CommonMethods* @Description: 公共方法* @author wenjianhai* @company 广州市道一信息技术有限公司* @date 2012-5-27* @version V1.0*/public final class CommonMethods {private static final Logger LOG = Logger.getLogger(CommonMethods.class);private CommonMethods() {}/*** @Title: parseSqlXML* @Description: 使用DOM4J解析xml文件* @param sqlXMLPath* xml文件路径* @param _node* xml节点* @return String* @author wenjianhai* @date 2012-5-27*/@SuppressWarnings("rawtypes")public static String parseSqlXML(String sqlXMLPath, String _node) {LOG.info("into CommonMethods.parseSqlXML(...)");LOG.info("the sqlXMLPath is:" + sqlXMLPath);LOG.info("the xml node is:" + _node);if ((null != _node && !"".equals(_node))&& (null != sqlXMLPath && !"".equals(sqlXMLPath))) {try {LOG.info("put the file '" + sqlXMLPath + "' into InputStream.");// 加载xml文件到输入流中InputStream is = CommonMethods.class.getClassLoader().getResourceAsStream(sqlXMLPath);//SAXReader reader = new SAXReader();// 读取xml文件,返回xml文档Document doc = reader.read(is);// 根节点Element root = doc.getRootElement();// 从当前节点的子节点中选择名称为_node的节点List rootList = root.selectNodes(_node);// xml元素Element element = null;// 返回的sqlString sql = null;// 循环此节点,并取出对应的文本信息for (Object obj : rootList) {element = (Element) obj;sql = element.getTextTrim();}// 关闭输入流closeStream(is, null);LOG.info("out of CommonMethods.parseSqlXML(...)");return sql;} catch (DocumentException e) {LOG.error("read xml file '" + sqlXMLPath + "' faile!", e);} catch (Exception e) {LOG.error("parse Sql XML '" + sqlXMLPath + "' faile!", e);}}LOG.info("the sqlXMLPath and _node is null,return null.");LOG.info("out of CommonMethods.parseSqlXML(...)");return null;}/*** @Title: closeStream* @Description: 关闭输入/输出流* @param is* : 字节输入流* @param os* : 字节输出流* @author wenjianhai* @date 2012-5-27*/public static void closeStream(InputStream is, OutputStream os) {if (null != is) {try {is.close();} catch (IOException e) {LOG.error("close InputStream faile!", e);}}if (null != os) {try {os.close();} catch (IOException e) {LOG.error("close OutputStream faile!", e);}}}
}
测试: 使用junit4
@Testpublic void parseSqlXML() {String _node = "sql/mywb/queryList";String sqlXMLPath = "cn/com/do1/component/mywb/resource/sql.xml";String sql = CommonMethods.parseSqlXML(sqlXMLPath, _node);System.out.println(sql);}
测试结果:
sql=select * from t_user
这篇关于使用dom4j解析指定节点下的信息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!