我想阅读这个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()在某种程度上不起作用。 谢谢你的帮助。
答案 0 :(得分:2)
类ExpressionEngine
的{{1}}实现不需要最顶层的标记(在您的情况下为XMLConfiguration
)作为搜索表达式的一部分。用<configuration>
替换搜索表达式可以解决您的问题。