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;
}