I am pretty new in XPath in Java and I have the following doubt related to this code that I found into a class on which I have to work:
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();
}
Where the ApplicationParameter input parameter of the previous method is this enum that is declared in the same class:
public enum ApplicationParameter {
cache_size,
restub_days,
upload_processes,
download_processes,
upload_bandwidth,
download_bandwidth
}
And CONFIG_DOCUMENT is a org.jdom.Document that contain the XML on which the previous method work.
So my doubt is: what exactly select this XPath query ?
xPath = XPath.newInstance("//root/settings/" + parameter.toString().replace("_", "-") );
n = (Element) xPath.selectSingleNode(CONFIG_DOCUMENT);
Tnx
Andrea
Given a document like this
the XPath expression selects the node I marked with ID
THIS
, and thus the whole method returns120
(n.getText()
). As a side note, it'd be better to useEnum.name()
instead oftoString()
to get the name of the constant, because toString() can be overridden to return a different text.