XMLConfiguration用法
XMLConfiguration是apache工具集里的一个用于对XML文件进行读写的东东,使用起来很方便。下面我将简单的举几个使用例子。
1,读
这里是我们的XML文件:unit.xml
<?xml version="1.0" encoding="utf-8"?>
<tree>
<unit id="root" type="root">
<back-ground>/root/Desktop/image/4.jpg</back-ground>
<unit id="1" type="alarm">
<back-ground>/root/Desktop/image/5.jpg</back-ground>
<father>root</father>
<position>x=250:y=225</position>
</unit>
</unit>
</tree>
下面是java代码:
//创建XMLConfiguration
private static XMLConfiguration getConfiguration(File file) {
if (file == null || !file.exists())
return null;
XMLConfiguration config = null;
try {
config = new XMLConfiguration(file);
} catch (ConfigurationException e) {
e.printStackTrace();
}
config.setEncoding("utf-8");//设置编码
return config;
}
.........
XMLConfiguration tool = getConfiguration("/home/dx/unit.xml");
//获取节点值
String rootBackGround = tool.getString("unit.back-ground");//这里获取的值是/root/Desktop/image/4.jpg
String alarmBackGround = tool.getString("unit.unit.back-ground");//这里获取的值是/root/Desktop/image/5.jpg
//获取节点属性
String rootID = tool.getString("unit[@id]");//这里获取的值是root
String alarmID = tool.getString("unit.unit[@id]");//这里获取的值是1
//获取重复节点值
如果有两个以上并级的节点如何区分呢?比如在第一级unit下有两个并列的unit:
......................................
<unit id="root" type="root">
<back-ground>/root/Desktop/image/4.jpg</back-ground>
<unit id="1" type="alarm">
<back-ground>/root/Desktop/image/5.jpg</back-ground>
<father>root</father>
<position>x=250:y=225</position>
</unit>
<unit id="2" type="alarm">
<back-ground>/root/Desktop/image/6.jpg</back-ground>
<father>root</father>
<position>x=300:y=270</position>
</unit>
</unit>
...............................
String firstID = tool.getString("unit.unit(0)[@id]");//这里获取的值是1
String secondID = tool.getString("unit.unit(1)[@id]");//这里获取的值是2
写操作基本基本更读的代码差不多(请先看上一篇:XMLConfiguration使用手记(1 读)) 只是这里我们用addProperty或setProperty
config.setProperty("unit.unit(0)[@id]", "0");
config.setProperty("unit.unit(1)[@id]", "1");
当然还是更读一样 要首先有个xml文件(空的也可以 但必须有根节点,其他节点会自动生成,当然也可以修改指定节点,方法还是一样的)。
这里要注意 XMLConfiguration默认情况下以','为分割符如果一个节点值里出现逗号 他会把他分开成两个节点例如:
config.setProperty("unit.unit", "a,b");
我们想要的结果是
...............................
<unit>
a,b
</unit>
.....................
可结果会变成
...............................
<unit>
a
</unit>
<unit>
b
</unit>
.....................
如果想要使用逗号 可以设置XMLConfiguration的delimiter例如
XMLConfiguration.setDelimiter(' ');//设置空格为分割符.
别望了写完save一下.
config.save();