XML上的XPath应用程序返回空字符串

时间:2018-04-28 03:11:10

标签: java xml xpath

我正在尝试使用xpath从xml获取值。以此模拟xml为例

<?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>

当我尝试使用此程序使用xpath字符串从此字符串中获取值时: -

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();

}

它返回一个空字符串而不是预期的

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

请你告诉我我做错了什么。

0 个答案:

没有答案