您的位置:首页 > 其它

XML[建模]

2019-05-27 19:36 218 查看

XML建模

建模的由来
就是将指定的xml字符串当作对象来操作

如果说当对一个指定的xml格式字符串完成了建模操作,

好处在于,只需要调用指定的方法就可以完成预定的字符串获取;

建模的思路

1、分析需要被建模的文件中有那几个对象
2、每个对象拥有的行为以及属性
3、定义对象从小到大(从里到外)
4、通过23种的设计模式中的工厂模式,解析xml生产出指定对象
好处:
提高代码的复用性

XML建模

我们用以下四个类来试验来获取 config.xml中的 属性
ConfigModel
ActionModel
ForwardModel
ConfigModelFactory

<config>
<action path="/regAction" type="test.RegAction">
<forward name="failed" path="/reg.jsp" redirect="false" />
<forward name="success" path="/login.jsp" redirect="true" />
</action>

<action path="/loginAction" type="test.LoginAction">
<forward name="b" path="/login.jsp" redirect="false" />
<forward name="success" path="/main.jsp" redirect="true" />
</action>
</config>

注:属性为String类型,子元素标签则是map的值,子元素标签的唯一标识则为map的值

实例化

建立ConfigModelFactory 工厂

public class ConfigModelFactory {
public static ConfigModel build() throws DocumentException {
return build("config.xml");
}

public  static ConfigModel build(String xmlPath) throws DocumentException {
ConfigModel configModel =new ConfigModel();
InputStream in = ConfigModelFactory.class.getResourceAsStream(xmlPath);
SAXReader saxreder=new SAXReader();
Document doc = saxreder.read(in);
ActionModel actionModel=null;
ForwardModel forwardModel=null;
List<Element> actionEles = doc.selectNodes("/config/action");
for (Element actionEle : actionEles) {
actionModel =new ActionModel();
//接下来需要往actionModel填充内容
actionModel.setPath(actionEle.attributeValue("path"));
actionModel.setType(actionEle.attributeValue("type"));
List<Element> forwardEles = actionEle.selectNodes("forward");
for (Element forwardEle : forwardEles) {
forwardModel =new ForwardModel();
forwardModel.setName(forwardEle.attributeValue("name"));
forwardModel.setPath(forwardEle.attributeValue("path"));
forwardModel.setRedirect(!"false".equals(forwardEle.attributeValue("redirect")));
actionModel.push(forwardM
1c6f4
odel);
}
configModel.push(actionModel);
}
return configModel;
}

public static void main(String[] args) throws DocumentException {
ConfigModel configModel =ConfigModelFactory.build();
ActionModel actionModel = configModel.pop("/regAction");
System.out.println(actionModel.getType());

ForwardModel forwardModel = actionModel.pop("success");
System.out.println(forwardModel.getPath()+"   "+ forwardModel.isRedirect());

}

}

最后取到属性相应的值

建模分两步:
1、以面向对象的编程思想,描述xml资源文件
2、将xml文件中内容封装进model实体对象。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: