Skip to content
Advertisement

How to get the node names under one parent node of XML in java

I have a situation where I need to get the node names of one XML file in java.

Here I want to get all the node names under “ns0:header”

sample XML file.

<SOAP-ENV:Envelope xmlns:SOAP-ENV="efefefff">
<SOAP-ENV:Body>
  <ns0:response_card_posted_transactions xmlns:ns0="fefefefeeff">


     <ns0:header>
        <ns0:version>1.0</ns0:version>
        <ns0:msg_id>78956285</ns0:msg_id>
        <ns0:msg_type>CCPT</ns0:msg_type>
        <ns0:msg_function>REP_CARD_POSTED_TRANSACTIONS</ns0:msg_function>
        <ns0:src_application>Src_APP</ns0:src_application>
        <ns0:target_application>CPS</ns0:target_application>
        <ns0:timestamp>01/06/2020 18:09:54</ns0:timestamp>
        <ns0:tracking_id>8032695</ns0:tracking_id>
        <ns0:bank_id>RICHBANK</ns0:bank_id>
     </ns0:header>
  </ns0:response_card_posted_transactions>

</SOAP-ENV:Body> </SOAP-ENV:Envelope>

I was trying getchildnodes() method but unable to find that.

Thanks Nihar

Advertisement

Answer

As you haven’t share your code, it is nearly impossible for me to understand the issue in your code. Here I’m sharing a simple code to parse the child node.

Steps:

  1. First you need to go to the <ns0:header> node.
  2. Then, try to get all the child nodes of that parent node.

Code:

public static void main(String[] args) throws Exception
{
    String xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV="efefefff"> <SOAP-ENV:Body> <ns0:response_card_posted_transactions xmlns:ns0="fefefefeeff"> <ns0:header> <ns0:version>1.0</ns0:version> <ns0:msg_id>78956285</ns0:msg_id> <ns0:msg_type>CCPT</ns0:msg_type> <ns0:msg_function>REP_CARD_POSTED_TRANSACTIONS</ns0:msg_function> <ns0:src_application>Src_APP</ns0:src_application> <ns0:target_application>CPS</ns0:target_application> <ns0:timestamp>01/06/2020 18:09:54</ns0:timestamp> <ns0:tracking_id>8032695</ns0:tracking_id> <ns0:bank_id>RICHBANK</ns0:bank_id> </ns0:header> </ns0:response_card_posted_transactions> </SOAP-ENV:Body> </SOAP-ENV:Envelope>";
    Document doc =
            DocumentBuilderFactory
                    .newInstance()
                    .newDocumentBuilder()
                    .parse(new InputSource(new StringReader(xml)));

    Node nl = doc.getElementsByTagName("ns0:header").item(0);
    NodeList headerChildNodes = nl.getChildNodes();
    for (int i = 0; i < headerChildNodes.getLength(); i++)
    {
        if (headerChildNodes.item(i) instanceof Element)
        System.out.println("Node is : "+headerChildNodes.item(i).getNodeName());
    }

}

Note: To get the child node text content simply use

System.out.println("Node is : "+headerChildNodes.item(i).getTextContent());

Output: Node: enter image description here

Text Content: enter image description here

Advertisement