使用apache commons配置xpath查询带有属性的空XML元素

Jam*_*gon 5 java xml xpath apache-commons apache-commons-config

我正在使用apache commons配置XMLConfiguration对象和XPATH表达式引擎来查询XML文件.我是xpath和apache commons的新手,我的语法有问题.

xml文件如下所示:

<attrs>
    <attr name="my_name" val="the_val"/>
    <attr name="my_name2" val="the_val2"/>
</attrs>
Run Code Online (Sandbox Code Playgroud)

我想要做的基本上是公共循环遍历所有属性并读取每行的名称和val.我可以解决所有问题的唯一方法是使用name的值再次查询xml.这种感觉对我来说不对,有没有更好的方法呢?

List<String> names = config.getList("attrs/attr/@name");
for( String name : names )
{
    String val = config.getString("attrs/attr[@name='" +name +"']/@val" );
    System.out.println("name:" +name +"   VAL:" +val);
}
Run Code Online (Sandbox Code Playgroud)

此外转换顶部到String,我不确定正确的方法来处理它.

Way*_*ett 4

一种选择是选择attr元素并将它们作为HierarchicalConfiguration对象进行迭代:

List<HierarchicalConfiguration> nodes = config.configurationsAt("attrs/attr");
for(HierarchicalConfiguration c : nodes ) {
    ConfigurationNode node = c.getRootNode();
    System.out.println(
        "name:" + ((ConfigurationNode) 
                            node.getAttributes("name").get(0)).getValue() +
        " VAL:" + ((ConfigurationNode) 
                            node.getAttributes("val").get(0)).getValue());
}
Run Code Online (Sandbox Code Playgroud)

这不是很漂亮,但是很有效。