总结
您可以尝试使用以下表达式,该表达式允许您选择节点,而无需考虑命名空间
ns0
:
/*[local-name()='GetADSLProfileResponse']/*[local-name()='Result']/*
解释
在您的语法中,有几个部分不正确。让我们一起看看。XPath语法
/xml
表示文档的根节点是
<xml>
,但根元素是
<ns0:GetADSLProfileResponse>
;
GetADSLProfileResponse
也不正确,因为XML文件包含命名空间。与相同
Result
:
/xml/GetADSLProfileResponse/Result
在我的解决方案中,我忽略了名称空间,因为您提供的名称空间不完整。以下是一个完整的入门计划:
String XML =
"<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n"
+ "<ns0:GetADSLProfileResponse xmlns:ns0 = \"http://\">\n"
+ " <ns0:Result>\n"
+ " <ns0:eCode>0</ns0:eCode>\n"
+ " <ns0:eDesc>Success</ns0:eDesc>\n"
+ " </ns0:Result>\n"
+ "</ns0:GetADSLProfileResponse> ";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document;
try (InputStream in = new ByteArrayInputStream(XML.getBytes(StandardCharsets.UTF_8))) {
document = builder.parse(in);
}
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("/*[local-name()='GetADSLProfileResponse']/*[local-name()='Result']/*");
NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println(node.getNodeName() + ": " + node.getTextContent());
}
它打印:
ns0:eCode: 0
ns0:eDesc: Success
另请参见: