0

I've got an XPath expression wherein, I'm trying to return all the child elements for that element, but I suspect that it's failing in java because I'm using "//". I've tested this expression in xpath tools and I know it works.

Here is my code:

public String getXPath(String xmlString) throws ParserConfigurationException,
            SAXException, IOException, XPathExpressionException {
        InputSource inputSource = new InputSource(new StringReader(xmlString));
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        String RecordCategory;


        Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputSource);

        // Create XPathFactory object
        XPathFactory xpathFactory = XPathFactory.newInstance();

        // Create XPath object
        XPath xpath = xpathFactory.newXPath();

        System.out.println("TESTING XPATH");

        XPathExpression expr = xpath.compile("//itl:testing[1]");
        RecordCategory = (String) expr.evaluate(doc,XPathConstants.STRING);
        System.out.println("THIS IS WHATS INSIDE RECORD CATEGORY: " + RecordCategory);

When attempting to print out the content of the request, I'm running the following code:

RecordCategory = (String) expr.evaluate(doc,XPathConstants.STRING);

But nothing seems to get printed....

I also tried it with this expression, and it sill did not work:

//*[name()='testing']

xml request:

<bookstore>

<itl:testing>
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</testing>

<itl:testing>
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</testing>

<itl:testing>
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</testing>

Am I doing something wrong?

MoStack
  • 1
  • 1
  • You have to declare the `itl` namespace prefix if you want to use it in your XPath. See duplicate link for further explanation and examples. – kjhughes Jul 06 '18 at 21:21
  • Also, your XML is not well formed. If that's not what you're really using, please take care to post true a [mcve] in the future. If it is what you're using, you'd see parsing errors. – kjhughes Jul 06 '18 at 21:24

0 Answers0