XML解析
对xml文件内部的配置解析之后可以用于框架的一些功能实现
XML的解析在java中分为四种方式:
- DOM(Document Object Model): 将整个xml文档内一次性加载完成,成为一个倒置的文档树,可以通过解析器在文档中任意遍历,适合少量的xml文件,对于大量的xml文件会消耗大量的内存,减低效率
- SAX(Simple Api For XML): 通过流媒体的方式,读取一部分元素,解析一部分,解析完毕之后释放内存,不会占用太多内存,但不能像DOM解析一样在文档任意节点读取。
- JDOM: 内部基于SAX解析的API实现,通过java实现XML解析,使用的是一些具体类解析
- DOM4J: 基于JDOM的优化分支,在JDOM基础上使用了大量的java的集合框架API的实现解析,并且DOM4J还支持快速节点索引方式(XPath)
使用小案列
1、创建一个java类XMLParse
2、创建一个java类User
3、在XMLParse类中定义一个User的Lisr集合user
public class XMLParse {
public List<User> parse(String xmlFileName) throws DocumentException {
List<User> user = new ArrayList<>();
//创建DOM4J解析器对象
SAXReader read = new SAXReader();
//获取指定文件的输入流
InputStream is = this.getClass().getResourceAsStream("/" + xmlFileName);
System.out.println(is);
// 加载流成为一个文档对象
Document doc = read.read(is);
//获取文档的根元素
Element root = doc.getRootElement();
// System.out.println(root.getName());
//获取根元素下的所有子元素
List list = root.elements("user");
for (Object o : list) {
Element e = (Element) o;
//获取元素中的id属性值
String id = e.attributeValue("id");
//获取当前元素的子元素中文本值
String name = e.element("name").getTextTrim();
String age = e.elementTextTrim("age");
String sex = e.elementTextTrim("sex");
User u = new User();
u.setUid(Integer.parseInt(id));
u.setName(name);
u.setSex(sex);
u.setAge(Integer.parseInt(age));
user.add(u);
}
return user;
}
public static void main(String[] args) throws DocumentException {
XMLParse xp = new XMLParse();
List<User> list = xp.parse("test.xml");
list.forEach(u-> System.out.println(u));
}
}
用XML创建数据库表
使用插件
1. dom4j-1.6.1.jar (xml解析时使用)
2. jaxen-1.1-beta-6.jar (快速节点索引)
3. mysql-connection-java-5.1.46.jar (数据库连接)
需要的资源
- 一个要创建的表格xml文件
- 一个连接数据库的数据xml文件
要创建的类
- ConfigReader
- TablGen
- Colum
- Config
- Table
实现
Colum类
public class Colum {
private String columName;
private String columType;
private int columLength;
public String getColumName() {
return columName;
}
public void setColumName(String columName) {
this.columName = columName;
}
public String getColumType() {
return columType;
}
public void setColumType(String columType) {
this.columType = columType;
}
public int getColumLength() {
return columLength;
}
public void setColumLength(int columLength) {
this.columLength = columLength;
}
@Override
public String toString() {
return "Colum{" +
"columName='" + columName + '\'' +
", columType='" + columType + '\'' +
", columLength=" + columLength +
'}';
}
}
Config类
public class Config {
private String driverClass;
private String url;
private String username;
private String password;
private List<Table> tables = new ArrayList<>();
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Table> getTables() {
return tables;
}
public void setTables(List<Table> tables) {
this.tables = tables;
}
@Override
public String toString() {
return "Config{" +
"driverClass='" + driverClass + '\'' +
", url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", tables=" + tables +
'}';
}
}
Table类
public class Table {
private String tabName;
private List<Colum> columns = new ArrayList<>();
public String getTabName() {
return tabName;
}
public void setTabName(String tabName) {
this.tabName = tabName;
}
public List<Colum> getColumns() {
return columns;
}
public void setColumns(List<Colum> columns) {
this.columns = columns;
}
@Override
public String toString() {
return "Table{" +
"tabName='" + tabName + '\'' +
", columns=" + columns +
'}';
}
}
ConfigReader类
public class ConfigReader {
private static String config = "config.xml";
/**
* 解析指定的xml文件成为一个document对象
* @param xmlFile
* @return
*/
public Document parse(String xmlFile) throws DocumentException {
//创建解析器
SAXReader read = new SAXReader();
// 加载指定文件成为一个输入流
InputStream is = this.getClass().getResourceAsStream("/" + xmlFile);
// 读取流中的内容成为一个document对象
Document doc = read.read(is);
return doc;
}
/**
* 读取配置文件中的信息成为一个document对象
* @return
*/
public Config read() throws DocumentException {
//获取核心配置文件的文档对象
Document doc = parse(config);
//List list = root.element("environments").element("environment").element("dataSource").elements("property");
//Xpath快速搜索节点
List<Node> list = doc.selectNodes("configuration/environments/environment/dataSource/property");
//初始化一个配置对象
Config conf = new Config();
//遍历集合获取property
list.forEach(node -> {
//获取节点中属性的值
String name = node.valueOf("@name");
String value = node.valueOf("@value");
System.out.println(name+"------->"+value);
//根据name属性值决定value属性值给Config对象的哪个属性
if(Objects.equals(name,"driver")){
conf.setDriverClass(value);
}else if(Objects.equals(name,"url")){
conf.setUrl(value);
}else if(Objects.equals(name,"username")){
conf.setUsername(value);
}else if(Objects.equals(name,"password")){
conf.setPassword(value);
}
});
//搜索mapper节点
List<Node> list1 = doc.selectNodes("configuration/mappers/mapper");
list1.forEach(node -> {
String mapperPath = node.valueOf("@resource");
//将指定的路劲xml资源读取成为一个table对象
Table table = readAsTable(mapperPath);
//将table对象加入集合
conf.getTables().add(table);
});
return conf;
}
/**
* 获取表的名称和列名、类型、长度
* @param mapperPath
* @return
*/
private Table readAsTable(String mapperPath) {
Table table = new Table();
try {
Document doc = parse(mapperPath);
//获取单个节点对象
Node nodeTab = doc.selectSingleNode("Mapper/table");
//获取表名称
String tableName = nodeTab.valueOf("@name");
table.setTabName(tableName);
//获取所有列信息
List<Node> list = nodeTab.selectNodes("property");
list.forEach(node -> {
Colum column = new Colum();
String cname = node.valueOf("@column");
String ctype = node.valueOf("@type");
String len = node.valueOf("@length");
column.setColumName(cname);
column.setColumType(ctype);
if(Objects.nonNull(len) && !Objects.equals(len,"")){
column.setColumLength(Integer.parseInt(len));
}
//将产生的列对象加入集合中
table.getColumns().add(column);
});
System.out.println(table.getColumns());
} catch (DocumentException e) {
e.printStackTrace();
}
return table;
}
TablGen类
public class TablGen {
private Config config;
public TablGen(Config config) {
this.config = config;
}
/**
* 获取数据库连接
* @return
*/
private Connection getConn(){
return null;
}
/**
* 根据table对象获取sql语句
* @param table
* @return
*/
private String getSql(Table table){
String sql = "create table "+table.getTabName()+"(";
//获取表中的所有列
List<Colum> columns = table.getColumns();
for (Colum c : columns) {
sql += c.getColumName() + " " + c.getColumType();
if (c.getColumLength() != 0){
sql += "(" + c.getColumLength()+")";
}
sql += ",";
}
sql = sql.substring(0,sql.length()-1)+ ')';
System.out.println("获取sql:"+sql);
return sql;
}
/**
* 创建表
* @param sql
*/
private void createTable(Connection conn,String sql) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
boolean f = ps.execute();
if(!f){
System.out.println("建表完成:"+sql);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public void execute() throws ClassNotFoundException, SQLException {
String driverClass = config.getDriverClass();
String url = config.getUrl();
String username = config.getUsername();
String password = config.getPassword();
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(url, username, password);
List<Table> tables = config.getTables();
for(Table table : tables) {
String sql = getSql(table);
createTable(conn,sql);
};
if(conn != null){
conn.close();
}
}
}
测试类Test
public class Test {
public static void main(String[] args) throws DocumentException, SQLException, ClassNotFoundException {
ConfigReader cr = new ConfigReader();
Config config = cr.read();
System.out.println("config是否空"+config);
TablGen tg = new TablGen(config);
tg.execute();
}
}