And*_*ili 0 java xml xpath jdom xml-parsing
我是Java中的XPath中的新手,我对这段代码有以下疑问,我发现在一个我必须工作的类中:
public String getApplicationParameter(ApplicationParameter parameter) {
Element n;
XPath xPath;
try {
xPath = XPath.newInstance("//root/settings/" + parameter.toString().replace("_", "-") );
n = (Element) xPath.selectSingleNode(CONFIG_DOCUMENT);
} catch (JDOMException e) {
return "";
}
if(n == null){
return "";
}
return n.getText();
}
Run Code Online (Sandbox Code Playgroud)
前一个方法的ApplicationParameter输入参数是在同一个类中声明的枚举:
public enum ApplicationParameter {
cache_size,
restub_days,
upload_processes,
download_processes,
upload_bandwidth,
download_bandwidth
}
Run Code Online (Sandbox Code Playgroud)
而CONFIG_DOCUMENT是org.jdom.Document中包含XML在其前面的方法工作.
所以我的疑问是:究竟选择这个XPath查询是什么?
xPath = XPath.newInstance("//root/settings/" + parameter.toString().replace("_", "-") );
n = (Element) xPath.selectSingleNode(CONFIG_DOCUMENT);
Run Code Online (Sandbox Code Playgroud)
TNX
安德里亚
给出这样的文件
<root>
<settings>
<cache-size id="THIS">120</cache-size>
<restub-days>6</restub-days>
</settings>
</root>
Run Code Online (Sandbox Code Playgroud)
XPath表达式选择我用ID标记的节点THIS,因此整个方法返回120(n.getText()).作为旁注,最好使用Enum.name()而不是toString()获取常量的名称,因为可以重写toString()以返回不同的文本.