1.什么叫XML建模
将XML配置文件中的元素、属性、文本信息转换成对象的过程叫做XML建模
-
XML建模
1)根据XML配置文件元素节点创建元素节点实体类
ConfigModel、ActionModel、ForwardModel
2)利用dom4j+xpath技术实现XML建模
ConfigModelFactoryDTD约束:由XML的根节点往里建立约束
XML建模:由最里层节点往根节点进行建模,一个元素节点代表一个实体
代码如下
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
/**
-
测试
-
@author 匡天明
*2020年7月15日17:14:05
*/
public class Demo {
private String defaultPath="/config.xml";public static void main(String[] args) {
Demo d=new Demo();
ConfigModel con=d.getModel();
System.out.println(con);
}public ConfigModel getModel() {
return this.getModel(defaultPath);
}
public ConfigModel getModel(String path) {
ConfigModel con=new ConfigModel();
try {
InputStream is=
Demo.class.getResourceAsStream(path);
SAXReader sax=new SAXReader();
//获取整个文档
Document doc = sax.read(is);
List action =doc.selectNodes("/config/action");
action.forEach(actions->{
//将节点文档转换为元素
Element actionele=(Element)actions;
//通过元素找到属性
String actionPath = actionele.attributeValue(“path”);
String actionType=actionele.attributeValue(“type”);
ActionModel actionmodel=new ActionModel();
actionmodel.setPath(actionPath);
actionmodel.setType(actionType);List<Node> forward = actionele.selectNodes("/config/action/forward"); forward.forEach(forwards->{ //将节点文档转换为元素 Element forwardele=(Element)forwards; String forwardName = forwardele.attributeValue("name"); String forwardPath = forwardele.attributeValue("path"); String forwardRedirect = forwardele.attributeValue("redirect"); ForwardModel fomo=new ForwardModel(); fomo.setName(forwardName); fomo.setPath(forwardPath); fomo.setRedirect(Boolean.parseBoolean(forwardRedirect)); actionmodel.push(fomo); }); con.push(actionmodel); }); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return con;
}
}