java Apache Commons XMLConfiguration - 如何在给定节点获取对象列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14388418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apache Commons XMLConfiguration - how to fetch a list of objects at a given node?
提问by Brendon Dugan
I have an XML configuration file similar to this:
我有一个与此类似的 XML 配置文件:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<config>
<mainServerHostname>MainServer</mainServerHostname>
<failoverServers>
<server>
<ipAddress>192.168.0.5</ipAddress>
<priority>1</priority>
</server>
<server>
<ipAddress>192.168.0.6</ipAddress>
<priority>2</priority>
</server>
</failoverServers>
</config>
Now, I know that by using the following code (after setting up my XMLConfiguration object and calling it config):
现在,我知道通过使用以下代码(在设置我的 XMLConfiguration 对象并调用它配置之后):
config.getList("failoverServers.server.ipAddress");
I can get a list of all of the ip addresses. This is handy, but what would be even more handy would be if I could do something like this:
我可以获得所有 IP 地址的列表。这很方便,但如果我能做这样的事情会更方便:
config.getList("failoverServers.server");
and get a list of Objects, each of which has an ipAddress and a priority. As far as I can tell though, there is no way to do this. Does anyone have any ideas on how I could accomplish this type of functionality? I would even be perfectly willing to define data structures corresponding to the structure of the XML that Java could map the data into if that would make things easier (in fact that would probably even be better). Thanks for the help all!
并获得一个对象列表,每个对象都有一个 ipAddress 和一个优先级。但据我所知,没有办法做到这一点。有没有人对我如何完成此类功能有任何想法?我什至完全愿意定义与 Java 可以将数据映射到的 XML 结构相对应的数据结构,如果这会让事情变得更容易(实际上这可能会更好)。感谢大家的帮助!
采纳答案by theadam
You can use HierarchicalConfiguration instead of XMLConfiguration. Works like this:
您可以使用 HierarchicalConfiguration 而不是 XMLConfiguration。像这样工作:
List<HierarchicalConfiguration> servers = config.configurationsAt("failoverServers.server");
for(HierarchicalConfiguration server : servers) {
System.out.println(server.getString("ipAddress"));
}
See: http://commons.apache.org/configuration/userguide/howto_xml.html
请参阅:http: //commons.apache.org/configuration/userguide/howto_xml.html