Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDOM 2 and xpath

Here is the following code excerpted from the 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 appears to be using JDOM 1.0 and I'd like to use JDOM 2.0.

How do I convert this code from JDOM 1.0 to JDOM 2.0? Why hasn't spring updated their sample code?

Thanks!

like image 534
Thom Avatar asked Aug 13 '12 19:08

Thom


1 Answers

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

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

like image 63
rolfl Avatar answered Oct 23 '22 10:10

rolfl