Dom4j的应用 xml的使用 android

Dom4j的应用 xml的使用
有的时候我们在程序中会有一些硬编码,这些硬编码是不可以改变的,在这个时候我们应该做的是 将那些硬编码提取出来,我的做法有两种:
1.建一个静态类,Constant.java 在里面存放系统所有的硬编码的变量
2.建立一个xml 文件,使用工具去读取该配置文件。这样的话就可以实现比较的系统。在xml中我们可以清晰的看到结点是怎么样的,从属关系是怎么样。
废话不多说,我之前在java程序中也用到了读取xml。但是将这个技术转移到android开发的时候,就发现了阻力。xml放在src的时候一直读取不了配置文件。然后我有了自己的解决方案,就是把他放在了assets文件中。来看代码:

<?xml version="1.0" encoding="UTF-8"?>
<relationshipRoot>
        <relationship name ="第一网格" pointX="0.84" pointY = "0.55" drawable="7f02001c"  src="relationShip_1.xml">
        </relationship>
        <relationship name ="第二网格" pointX="0.75" pointY = "0.35" drawable="7f02001d"  src="relationShip_2.xml">
        </relationship>
        <relationship name ="第三网格" pointX="0.62" pointY = "0.35" drawable="7f02001e"  src="relationShip_3.xml">
        </relationship>
        <relationship name ="第四网格" pointX="0.5" pointY = "0.5" drawable="7f02001f"  src="relationShip_4.xml">
        </relationship>
        <relationship name ="第五网格" pointX="0.4" pointY = "0.5" drawable="7f020020" src="relationShip_5.xml">
        </relationship>
        <relationship name ="第六网格" pointX="0.1" pointY = "0.4" drawable="7f020021"  src="relationShip_6.xml">
        </relationship>
</relationshipRoot>`

这是我们要进行的读取xml 文件的内容。

//调用
list = reader.relationShipReader(this.getAssets().open("relationshipMapper.xml"));

//方法
public List<Map<String,String>> relationShipReader(InputStream is){
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
         try {

             reader = new SAXReader();
             //读取配置
             doc = reader.read(is);
             //得到根目录
             Element root = doc.getRootElement();
             list = new ArrayList<Map<String,String>>();
             //得到该结点下的所有结点
             List<Element> relationshipList = root.elements();
             //循环得到 并且将其存入到list<Map<String,Stirng>> 中去
             for(Element element:relationshipList){
                 Map<String,String> map = new HashMap<String,String>();
                 map.put("name",element.attribute("name").getValue());
                 map.put("pointX",element.attributeValue("pointX"));
                 map.put("pointY",element.attributeValue("pointY"));
                 map.put("drawable",element.attributeValue("drawable"));
                 map.put("src", element.attributeValue("src"));
                 list.add(map);
             }
         } catch (DocumentException e) {
             e.printStackTrace();
         }

         return list;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值