Search code examples
javaxmlxpathnodelist

how to parse xml to java in nodelist


that is my 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> 

that is my code in java I need to know how to start in this I tried some code online but still did not solve my problem how to get the values in the result to loop in it and get 0 in ecode and Success in 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){

        } 

Solution

  • Summary

    You can try to following expression which allows you to select nodes without caring the namespace ns0:

    /*[local-name()='GetADSLProfileResponse']/*[local-name()='Result']/*
    

    Explanation

    In your syntax, several parts were incorrect. Let's take a look together. XPath syntax /xml means that the root node of the document is <xml>, but the root element is <ns0:GetADSLProfileResponse>; GetADSLProfileResponse is incorrect too, because your XML file contains a namespace. Same for Result:

    /xml/GetADSLProfileResponse/Result
    

    In my solution, I ignored the namespace, because your namespace provided is incomplet. Here's a full program to get started:

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

    It prints:

    ns0:eCode: 0
    ns0:eDesc: Success
    

    See also: