那是我的XML
<?xml version = "1.0" encoding = "UTF-8"?>
<ns0:GetADSLProfileResponse xmlns:ns0 = "http://">
<ns0:Result>
<ns0:eCode>0</ns0:eCode>
<ns0:eDesc>Success</ns0:eDesc>
</ns0:Result>
</ns0:GetADSLProfileResponse>
这是我在 Java 中的代码,我需要知道如何从中开始 我在网上尝试了一些代码,但仍然没有解决我的问题 如何让结果中的值在其中循环并在 eCode 中获取 0 并在 eDesc 中成功
CustomerProfileResult pojo = new CustomerProfileResult();
String body = readfile();
System.out.println(body);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(new InputSource(new StringReader(body)));
XPath xpath =XPathFactory.newInstance().newXPath();
XPathExpression name = xpath.compile("/xml/GetADSLProfileResponse/Result");
NodeList nodeName = (NodeList) name.evaluate(dom, XPathConstants.NODESET);
if(nodeName!=null){
}
总结
您可以尝试以下表达式,该表达式允许您选择节点而不关心命名空间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
另请参阅:
- 如何使用 XPath 在 Java 中使用命名空间查询 XML?
- 节点(Java Platform SE 8(