如何在节点列表中将 xml 解析为 java

how to parse xml to java in nodelist

那是我的 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){

        } 

总结

您可以尝试使用以下表达式,它允许您 select 节点而不关心命名空间 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

另请参阅: