0

I have a XML file like the following.

<?xml version="1.0" encoding="UTF-8"?>
<Site>
  <Name>MySite</Name>
  <Groups>
      <Default></Default>
      <GroupA></GroupA>
  </Groups>
</Site>

I want to get all names of Groups' children elements (in this example 'Default' and 'GroupA') as a list of strings. I was trying the following.

public List<String> getGroupNames() {
    List<String> names = new ArrayList<String>();

    XPathExpression<Text> xpath = XPathFactory.instance().compile(
            "/Site/Groups/*/name()", Filters.text());

    List<Text> elements = xpath.evaluate(document);

    if (elements.size() > 0) {
        for (Text text : elements) {
            names.add(text.getText());
        }
        return names;
    }
    return null;
}

This fails hard with the following exception.

class org.jaxen.saxpath.XPathSyntaxException: /Site/Groups/*/name(): 20: Expected node-type

What is the proper syntax for that? I do not understand the exception.

Tony Stark
  • 2,318
  • 1
  • 22
  • 41

1 Answers1

0

It seems the XPathFactory instance you use only supports XPath 1.

You need to load a library supporting XPath 2, before being able using xpath 2. E.g: with SAXON:

import net.sf.saxon.om.NamespaceConstant;  


String objectModel = NamespaceConstant.OBJECT_MODEL_SAXON;  
System.setProperty("javax.xml.xpath.XPathFactory:"+objectModel, "net.sf.saxon.xpath.XPathFactoryImpl");  
BeniBela
  • 16,412
  • 4
  • 45
  • 52