XML建模

1.什么叫XML建模
将XML配置文件中的元素、属性、文本信息转换成对象的过程叫做XML建模

  1. XML建模
    1)根据XML配置文件元素节点创建元素节点实体类
    ConfigModel、ActionModel、ForwardModel
    2)利用dom4j+xpath技术实现XML建模
    ConfigModelFactory

    DTD约束:由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;
    

    }
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值