xml的Xpath表达式评估返回空的“”

时间:2018-08-31 20:12:26

标签: java xml xpath

我正在尝试通过XPath表达式获取XML的节点值,如以下代码所示。

返回空值,尽管在xpath-tester上求值时返回正确的节点值

private String getNodeValue(){  
        String nodeVal=null;
        try {

        XPath xPath = XPathFactory.newInstance().newXPath();
          String testData="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
                + "<provider xmlns=\"http://www.test.com/test-message\">\r\n" + 
                "<header>\r\n" + 
                "<TmStp>2013-12-25T08:52:595</TmStp>\r\n" + 
                "<GUID>testguid64886</GUID>\r\n" + 
                "</header>\r\n" + 
                "<service>\r\n" + 
                "<name>name</name>\r\n" + 
                "<type>type</type>\r\n" + 
                "</service>\r\n" + 
                "</provider>";
         InputSource inputSource = new InputSource(new StringReader(testData));
         nodeVal = (String) xPath.compile("/provider/header").evaluate(inputSource);
         System.out.println("Node Value "+nodeVal);  //output is empty  >>>> Node Value []

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return nodeVal;
    }

上面的代码的原始XML部分是:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<provider xmlns="http://www.test.com/test-message"> 
    <header>
        <TmStp>2013-12-25T08:52:595</TmStp>
        <GUID>testguid64886</GUID>        
    </header>
    <service>
        <name>name</name>
        <type>type</type>
    </service>    
</provider>

原始的XPath表达式是:

/provider/header

0 个答案:

没有答案