Apache Commons-configuration 学习笔记3

读取XML
假如有个XML,名叫:XMLtest.xml如下:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<gui-definition>
<colors>
<background>#808080</background>
<text>#000000</text>
<header>#008000</header>
<link normal="#000080" visited="#800080"/>
<default>${colors.header}</default>
</colors>
<rowsPerPage>15</rowsPerPage>
<buttons>
<name>OK,Cancel,Help</name>
<name>Yes,No,Cancel</name>
</buttons>
<numberFormat pattern="###\,###.##"/>
</gui-definition>

标准的XML文件都会有一个跟标签包裹住所有内容,这个标签的子标签认为是顶级名字空间
(这个说法可能不准确)不多说了看代码吧
XMLConfiguration config = new XMLConfiguration("XMLtest.xml");
/**
*<colors>
* <background>#808080</background>
* <text>#000000</text>
* <header>#008000</header>
* <link normal="#000080" visited="#800080"/>
* <default>${colors.header}</default>
*</colors>
*这是从上面的xml中摘抄的一段,我们现在来解析它,
*colors是根标签下的直接子标签,所以是顶级名字空间
*/
String backColor = config.getString("colors.background");
String textColor = config.getString("colors.text");
//现在我们知道了如何读取标签下的数据,那么如何读标签中的属性呢?看下面
//<link normal="#000080" visited="#800080"/>
String linkNormal = config.getString("colors.link[@normal]");
//还支持引用呢!
//<default>${colors.header}</default>
String defColor = config.getString("colors.default");
//也支持其他类型,但是一定要确定类型正确,否则要报异常哦
//<rowsPerPage>15</rowsPerPage>
int rowsPerPage = config.getInt("rowsPerPage");

/**
*但是我们如何读取List呢
*看这里:
*<buttons>
* <name>OK,Cancel,Help</name>
* <name>Yes,No,Cancel</name>
*</buttons>
*/
这时我们可以用:
List buttons = config.getList("buttons.name");
for(String button:buttons){
System.out.println(button);
}
但是显示的是
OK
Cancel
Help
Yes
No
Cancel
我们想要的是
OK,Cancel,Help
Yes,No,Cancel
如果看过之前的文章就会知道,我们有一些设置没有设
也就是我们要禁用List分隔符delimiter.在AbstractionConfiguration
这个类中(XMLConfiguration的父类)有这个setDelimiterParsingDisabled方法可以
禁用分隔符。但是要在读取XML文件之前设置这个属性。所以代码改为
XMLConfiguration config = new XMLConfiguration();
config.setDelimiterParsingDisabled(true);
config.setFileName("XMLtest.xml");
config.load();
List<String> buttons = config.getList("buttons.name");
for(String button:buttons){
System.out.println(button);
}
这就可以了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值