Home > Software engineering >  Read XML file using DOM Java
Read XML file using DOM Java

Time:12-26

Below is my XML file,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SampleDTO>
<mInfo>
    <aName>FMgr</aName>
</mInfo>

<Result xsi:type="ResultDTO">
    <pname>Module1</pname>
    <proname>com.test.Manager</proname>
    <caseResult xsi:type="ResultDTO">
        <failure>0</failure>
        <aResult xsi:type="ARDTO">
            <aName>AAAA</aName>
        </aResult>
        <aResult xsi:type="ARDTO">
            <aName>BBBB</aName>
        </aResult>
    </caseResult>
</Result>

<Result xsi:type="ResultDTO">
    <pname>Module2</pname>
    <proname>com.test.Manager</proname>
    <caseResult xsi:type="ResultDTO">
        <failure>0</failure>
        <aResult xsi:type="ARDTO">
            <aName>CCCC</aName>
        </aResult>
        <aResult xsi:type="ARDTO">
            <aName>DDDD</aName>
        </aResult>
    </caseResult>
</Result>

</SampleDTO>

Java code:

File file = new File("...//filepath");  
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
DocumentBuilder db = dbf.newDocumentBuilder();  
Document doc = db.parse(file);  
doc.getDocumentElement().normalize(); 


NodeList nodeList = doc.getElementsByTagName("caseResult");  
for (int itr = 0; itr < nodeList.getLength(); itr  )   
{  
    Node node = nodeList.item(itr);  
    if (node.getNodeType() == Node.ELEMENT_NODE)   
    {  
        Element eElement = (Element) node;
        System.out.print(eElement.getElementsByTagName("aName").item(0).getTextContent());  
        
    } 
}

I can able to get the list of caseResult by using DOM in java. I want to get both the caseResult and <aName>FMgr</aName>and <proname>com.test.Manager</proname>. Hot to get all in one.

CodePudding user response:

try with following solution

NodeList resultNodeList = document.getElementsByTagName("Result");
for (int i = 0; i < resultNodeList.getLength(); i  ) {
    Element resultNodeElement = (Element) resultNodeList.item(i);
    String proname = resultNodeElement.getElementsByTagName("proname").item(0).getTextContent();
          
    Element caseResultElement = (Element) resultNodeElement.getElementsByTagName("caseResult").item(0);
          
    NodeList aResultNodeList = caseResultElement.getElementsByTagName("aResult");
    for (int y = 0; y < aResultNodeList.getLength(); y  ) {
        Element aResultElement = (Element) aResultNodeList.item(i);
        String aName = aResultElement.getElementsByTagName("aName").item(0).getTextContent();
    }
}
  • Related