JDOM 2 and xpath

Here is the following code taken from Spring-ws manual:

public class HolidayEndpoint {

  private static final String NAMESPACE_URI = "http://mycompany.com/hr/schemas";

  private XPath startDateExpression;

  private XPath endDateExpression;

  private XPath nameExpression;

  private HumanResourceService humanResourceService;

  @Autowired
  public HolidayEndpoint(HumanResourceService humanResourceService)                      (2)
      throws JDOMException {
    this.humanResourceService = humanResourceService;

    Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);

    startDateExpression = XPath.newInstance("//hr:StartDate");
    startDateExpression.addNamespace(namespace);

    endDateExpression = XPath.newInstance("//hr:EndDate");
    endDateExpression.addNamespace(namespace);

    nameExpression = XPath.newInstance("concat(//hr:FirstName,' ',//hr:LastName)");
    nameExpression.addNamespace(namespace);
  }

My problem is that this is similar to using JDOM 1.0, and I would like to use JDOM 2.0.

How do I convert this code from JDOM 1.0 to JDOM 2.0? Why didn't spring update its sample code?

Thank!

+5
source share
2 answers

JDOM2 is still relatively new .... but the XPath factory in JDOM 1.x is especially broken ... and JDOM 2.x has a new api for it. The old API exists for backward compatibility / migration. Take a look at this document here for some discussion, and the new API in 2.x the JDOM .

In your case, you probably want to replace the code with something like:

XPathExpression<Element> startDateExpression = 
    XPathFactory.instance().compile("//hr:StartDate", Filters.element(), null, namespace);

List<Element> startdates = startDateExpression.evaluate(mydocument);

Rolf

+7
source

Rolf, , .

List<Element> startdates = startDateExpression.evaluate(mydocument);

    for (Element e: startdates){
        logger.debug("value= " + e.getValue());
    }

List<Element> startdates = startDateExpression.evaluate(mydocument);
logger.debug("value " + startdates.get(0).getValue();
0

All Articles