What exactly select this XPath query?

79 views Asked by At

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

1

There are 1 answers

0
Raffaele On BEST ANSWER

Given a document like this

<root>
  <settings>
    <cache-size id="THIS">120</cache-size>
    <restub-days>6</restub-days>  
  </settings>
</root>

the XPath expression selects the node I marked with ID THIS, and thus the whole method returns 120 (n.getText()). As a side note, it'd be better to use Enum.name() instead of toString() to get the name of the constant, because toString() can be overridden to return a different text.