xml建模的由来
将指定的xml字符串当作对象来操作
如果说当对一个指定的xml格式字符串完成了建模操作,
好处在于,只需要调用指定的方法就可以完成预定的字符串获取;
建模的思路
1、分析需要被建模的文件中有那几个对象
2、每个对象拥有的行为以及属性
3、定义对象从小到大(从里到外)
4、通过23种的设计模式中的工厂模式,解析xml生产出指定对象
xml建模案例
封装.xml文件里的属性
创建一个工厂类来生产指定模型对象方法
- 获取path路径
InputStream in= ConfigModelFactory.class.getResourceAsStream(path);
SAXReader reader=new SAXReader();
- 读取.xml里的内容
Document doc = reader.read(in);
- 把内容填充到模型对象中
//把内容填充到configmodel对象中 doc-->configmodel
ConfigModel configmodel=new ConfigModel();
ActionModel actionmodel=null;
ForwardModel forwardmodel=null;
List<Element> actionEles=doc.selectNodes("/config/action");
for (Element actionEle : actionEles) {
actionmodel.setPath(actionEle.attributeValue("path"));
actionmodel.setType(actionEle.attributeValue("type"));
//给actionmodel中放入forwardmodel对象
List<Element> forwardEles = actionEle.selectNodes("forward");
for (Element forwardEle : forwardEles) {
forwardmodel=new ForwardModel();
forwardmodel.setName(forwardEle.attributeValue("name"));
forwardmodel.setPath(forwardEle.attributeValue("path"));
//redirect属性是boolean
//需求:只有config.xml中redirect属性值填写了false,它才代表转发
forwardmodel.setRedirect(!"false".equals(forwardEle.attributeValue("redirect")));
}
configmodel.push(actionmodel);
}
测试
public static void main(String[] args) throws Exception {
ConfigModel model = ConfigModelFactory.build();
ActionModel actionModel = model.pop("/LoginAction");
System.out.println(actionModel.getType());
}