简体   繁体   中英

Java XML parser loop thru repetitive XML and grab a specific node

I'm working with Java and I have an XML file with repetitive nodes with the same names. I need to grab the 1st <Calculation_Results Mass="1234"> , its child nodes and loop thru them to insert a database row, then grab the 2nd, 3rd, xxx and do the same for each node section. The problem I'm having is: since the child nodes are all the same name, the Calculation_Result child from every node section is grabbed every time I loop through them.

File inputFile = new File("TestSet01_Network.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();

NodeList calcResults = doc.getElementByTagName("Calculation_Results");
   for (int a=0;a<calcResults.getLength();a++) {
      NodeList calcChildNodes = calcResults.getElementByTagName("Calculation_Result"); 
         for (int b=0;b<calcResults.getLength();b++) {
            String name = calcChildNodes.item(b).getAttributes().getNamedItem("Name").getTextContent();
            String value = calcChildNodes.item(b).getAttributes().getNamedItem("Value").getTextContent();

           **Insert rows into database**
   }
}

XML Example:

<Calculation_Results Mass="1234">
  <Calculation_Result Name="Name1" Value="Value1"/>
  <Calculation_Result Name="Name2" Value="Value2"/>
  <Calculation_Result Name="Name3" Value="Value3"/>
</Calculation_Results>
<Calculation_Results Mass="5678">
  <Calculation_Result Name="Name1" Value="Value10"/>
  <Calculation_Result Name="Name2" Value="Value20"/>
  <Calculation_Result Name="Name3" Value="Value30"/>
</Calculation_Results>
<Calculation_Results Mass="9876">
  <Calculation_Result Name="Name1" Value="Value100"/>
  <Calculation_Result Name="Name2" Value="Value200"/>
  <Calculation_Result Name="Name3" Value="Value300"/>
</Calculation_Results>

This line is getting all children every time
NodeList calcChildNodes = calcResults.getElementByTagName("Calculation_Result");

Getting child starting at the proper element should get the expected result

NodeList calcResults = doc.getElementByTagName("Calculation_Results");
   for (int a=0;a<calcResults.getLength();a++) {
      NodeList calcChildNodes = calcResults.item(a).getElementByTagName("Calculation_Result"); 
         for (int b=0;b<calcChildNodes.getLength();b++) {
            String name = calcChildNodes.item(b).getAttributes().getNamedItem("Name").getTextContent();
            String value = calcChildNodes.item(b).getAttributes().getNamedItem("Value").getTextContent();

           **Insert rows into database**
   }
}

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