1

I am trying to fetch value from xml using xpath. Take this mock xml for example

<?xml version="1.0" encoding="UTF-8" ?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body></SOAP-ENV:Body></SOAP-ENV:Envelope>

When I am trying to fetch value from this string using xpath string with this program: -

public static String getXPathValue(String stringSource) {
    String stringCompile = "/SOAP-ENV:Envelope";     

    StringBuilder stringBuilder = new StringBuilder();
    XPathFactory pathFactory = XPathFactory.newInstance();
    XPath path = pathFactory.newXPath();
    try {
        XPathExpression pathExpression = path.compile(stringCompile);
        Object result = pathExpression.evaluate(new InputSource(
                new StringReader(stringSource)), XPathConstants.STRING);

        if (result instanceof String) {
            stringBuilder.append(result.toString());
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    System.out
            .println("Returned string is "+stringBuilder.toString());
    return stringBuilder.toString();

}

It returns me an empty string instead of the expected

<SOAP:ENV:Envelope xmlns:SOAP:ENV="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP:ENV:Header/>
  <SOAP:ENV:Body/></SOAP:ENV:Envelope>

Can u please suggest me what I am doing wrong.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Adi
  • 387
  • 3
  • 6
  • 14

0 Answers0