我正在开一个类来加载 XML文件配置,这个类扩展自 XMLConfiguration. 配置文件如下所示: ?xml version="1.0" encoding="UTF-8"?root global reloadInterval5/reloadInterval /global definitions definition id1/id nameTest na
配置文件如下所示:
<?xml version="1.0" encoding="UTF-8"?> <root> <global> <reloadInterval>5</reloadInterval> </global> <definitions> <definition> <id>1</id> <name>Test name</name> <messages> <message id="1">Help menu opt 1</message> <message id="2">Help menu opt 2</message> <message id="3">Help menu opt 3</message> </messages> </definition> </definitions> </root>
我迭代这个和加载的方式如下:
private void updateDefinitions() { this.definitions.clear(); List<SubnodeConfiguration> lstDefinitions = getListConfig("definitions"); for(SubnodeConfiguration definition : lstDefinitions) { DefinitionBean aDefinition = new DefinitionBean(); aDefinition.setId(definition.getInt("Definition.id", -1)); aDefinition.setName(definition.getString("Definition.name", "")); List<MessageBean> messages = new ArrayList<MessageBean>(); List<SubnodeConfiguration> lstMessages = definition.configurationsAt("definition.messages"); for(SubnodeConfiguration messageBean : lstMessages) { MessageBean message = new MessageBean(); message.setId(messageBean.getString("message")); messages.add(message); } definition.setMessages(messages); this.definitions.put(aDefinition.getId(), aDefinition); } }
代码工作正常,但问题是获取每个< message>的id属性.元素,我不知道如何检索它. SubnodeConfiguration的getter都没有提供这个,或者也许,我没有以正确的方式做到这一点.
任何帮助将不胜感激.
我看到你的评论,但它也在 documentation here.SubnodeConfiguration扩展了HierarchicalConfiguration.此外,如果使用方法HierarchicalConfiguration.configurationsAt()检索配置,并且您正在检索的节点本身具有属性,则只需使用方括号@ notation访问它.例如:
XML:
<foos> <foo bar='bazz'/> <foo bar='bizz'/> <foo bar='buzz'/> </foos>
Java的:
// load xml into config XmlConfiguration config = ... List<HierarchicalConfiguration> foos = config.configurationsAt("foo"); for (HierarchicalConfiguration foo : foos) { System.out.println(foo.getString("[@bar]")); }
应打印:
bazz bizz buzz