0

我想阅读这个 xml 文件:

<configuration>
 <parameter name="path">C:\Users\bellibot\Desktop</parameter>
 <parameter name="filename">config.xml</parameter>
 <module type="livestatus" id="0001">
   <parameter name="username">nagiosadmin</parameter>
   <parameter name="password">nagiosadmin</parameter>
   <parameter name="hostaddress">127.0.0.1/nagios/live.php?q=</parameter>  
</configuration>   

使用此代码:

class XMLslave {
XMLConfiguration config;
String defval = "DEFAULT";


public XMLslave(){}

public XMLslave(String path, String filename){
    try{
    String str = path + "\\" + filename;
    File file = new File(path, filename); 
    this.config = new XMLConfiguration(file);
    this.config.setExpressionEngine(new XPathExpressionEngine());
    }catch(ConfigurationException e){}
}

public static void main(String[] args) {
    try{
    BufferedReader in = new BufferedReader(
            new InputStreamReader(System.in));
    System.out.println("Insert Path");
    String path = in.readLine();
    System.out.println("Insert Filename");
    String filename = in.readLine();
    XMLslave slave = new XMLslave(path, filename);
    String str = slave.getKey("path");   
    System.out.println(str);    
    }catch (IOException e){}
}

String getKey(String key){
    String result;
    String str = "/configuration/parameter[@name='" + key + "']";
    result = this.config.getString(str);
    if (result==null){
        return this.defval;
    }else{
        return result;}
    }

我不明白为什么返回值是“DEFAULT”而不是“C:\Users\bellibot\Desktop”,我测试了 xpath 语法并且它是合法的,我相信 config.getString() 不知何故不起作用。谢谢您的帮助。

4

1 回答 1

2

类的ExpressionEngine实现XMLConfiguration不需要最顶部的标记(<configuration>在您的情况下)是搜索表达式的一部分。将您的搜索表达式替换为String str = "parameter[@name='" + key + "']";将解决您的问题。

于 2013-11-03T18:15:24.600 回答