简体   繁体   中英

Not able to parse inner elements of XML using DocumentBuilderFactory in Java

I'm having a response as XML. I'm trying to parse the XML object to get inner details. Im using DocumentBuilderFactory for this. The parent object is not null, but when I try to get the deepnode list elements, its returning null. Am I missing anything

Here is my response XML

ResponseXML

<DATAPACKET REQUEST-ID = "1">
<HEADER>        
</HEADER>
<BODY>      
    <CONSUMER_PROFILE2>
        <CONSUMER_DETAILS2>             
            <NAME>David</NAME>
            <DATE_OF_BIRTH>1949-01-01T00:00:00+03:00</DATE_OF_BIRTH>
            <GENDER>001</GENDER>
        </CONSUMER_DETAILS2>
      </CONSUMER_PROFILE2></BODY></DATAPACKET>

and Im parsing in the following way

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(responseXML));
// Consumer details.

if(doc.getDocumentElement().getElementsByTagName("CONSUMER_DETAILS2") != null) {              
            Node consumerDetailsNode = doc.getDocumentElement().getElementsByTagName("CONSUMER_DETAILS2").item(0); -->This is coming as null                
            dateOfBirth = getNamedItem(consumerDetailsNode, "DATE_OF_BIRTH");                               
            System.out.println("DOB:"+dateOfBirth);             

        }

getNamedItem

private static String getNamedItem(Node searchResultNode, String param) {
    return searchResultNode.getAttributes().getNamedItem(param) != null ? searchResultNode.getAttributes().getNamedItem(param).getNodeValue() : "";
}

Any ideas would be greatly appreciated.

The easiest way to search for individual elements within an XML document is with XPAth . It provides search syntax similar to file system notation. Here is a solution to the specific problem of you document:

EDIT: solution adopted to support multiple CONSUMER_PROFILE2 elements. You just need to get and parse NodeList instread of one Node

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class XpathDemo
{
    public static void main(String[] args)
    {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document xmlDoc = builder.parse(new InputSource(new FileReader("C://Temp/xx.xml")));

            // Selects all CONSUMER_PROFILE2 elements no matter where they are in the document
            String cp2_nodes = "//CONSUMER_PROFILE2";
            // Selects first DATE_OF_BIRTH element somewhere under current element
            String dob_nodes = "//DATE_OF_BIRTH[1]";
            // Selects text child node of current element
            String text_node = "/child::text()";

            XPath xPath =  XPathFactory.newInstance().newXPath();
            NodeList dob_list = (NodeList)xPath.compile(cp2_nodes + dob_nodes + text_node)
                    .evaluate(xmlDoc, XPathConstants.NODESET);
            for (int i = 0; i < dob_list.getLength() ; i++) {
                Node dob_node = dob_list.item(i);
                String dob_text = dob_node.getNodeValue();
                System.out.println(dob_text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM