转自:
下文笔者讲述Mybatis之xml配置解析的相关简介说明,如下所示
下文笔者讲述使用XMLConfigBuilder类
读取xml文件并生成一个DataSource
使用xml配置一个DataSource
xml格式如下所示:
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/mysqldb?useUnicode=true&characterEncoding=utf8 root 123456
dom4j可用于读取每一个节点的标签、属性、子节点等
而且使用较为简单,只需要输入流或文件即可解析
例: 使用dom4j,先引入dom4j相应的jar包
dom4j dom4j 1.6.1
编写相应的示例代码
// InputStream in; SAXReader reader = new SAXReader(); Document document = reader.read(in); Element root = document.getRootElement(); String tagName = root.getName(); // 标签名 for (Object item : root.elements("xxx")) { // e表示root的标签名为xxx的孩子 Element e = (Element) item; }
XMLConfigure之获取配置信息
private static ClassLoader loader = ClassLoader.getSystemClassLoader(); public static DataSource build(String resource) { try { InputStream stream = loader.getResourceAsStream(resource); SAXReader reader = new SAXReader(); Document document = reader.read(stream); Element root = document.getRootElement(); // Element代入,生成DataSource return evalDataSource(root); } catch (Exception e) { throw new RuntimeException("error occured while evaling xml " + resource); } } //内容解析 public static DataSource evalDataSource(Element node) throws ClassNotFoundException { if (!node.getName().equals("database")) { throw new RuntimeException("root should be"); } String driverClassName = null; String url = null; String username = null; String password = null; for (Object item : node.elements("property")) { Element i = (Element) item; String value = getValue(i); String name = i.attributeValue("name"); if (name == null || value == null) throw new RuntimeException("[database]: should contain name and value"); switch (name) { case "url" : url = value; break; case "username" : username = value; break; case "password" : password = value; break; case "driverClassName" : driverClassName = value; break; default : throw new RuntimeException("[database]: unknown name"); } } return new VDataSource(driverClassName, url, username, password); } //测试代码 DataSource ds = XMLConfigBuilder.build("config.xml"); Session session = new VSession(data); session.exec("select * from users where id<8");