A simple way to Iterate on XML tree and extract data from it?

moyrehalbio

New Member
Assuming that I have four levels in my XML tree , where level 3 can have the same son - twice , i.e. in the following XML : \[code\]<Game> <Round> <roundNumber>1</roundNumber> <Door> <doorName>abd11</doorName> <Value> <xVal1>0</xVal1> <xVal2>25</xVal2> <pVal>0.31</pVal> </Value> <Value> <xVal1>25</xVal1> <xVal2>50</xVal2> <pVal>0.04</pVal> </Value> <Value> <xVal1>50</xVal1> <xVal2>75</xVal2> <pVal>0.19</pVal> </Value> <Value> <xVal1>75</xVal1> <xVal2>100</xVal2> <pVal>0.46</pVal> </Value> </Door> <Door> <doorName>vvv1133</doorName> <Value> <xVal1>60</xVal1> <xVal2>62</xVal2> <pVal>1.0</pVal> </Value> </Door> </Round> <Round> <roundNumber>2</roundNumber> <Door> <doorName>eee</doorName> <Value> <xVal1>0</xVal1> <xVal2>-25</xVal2> <pVal>0.31</pVal> </Value> <Value> <xVal1>-25</xVal1> <xVal2>-50</xVal2> <pVal>0.04</pVal> </Value> <Value> <xVal1>-50</xVal1> <xVal2>-75</xVal2> <pVal>0.19</pVal> </Value> <Value> <xVal1>-75</xVal1> <xVal2>-100</xVal2> <pVal>0.46</pVal> </Value> </Door> <Door> <doorName>cc</doorName> <Value> <xVal1>-60</xVal1> <xVal2>-62</xVal2> <pVal>0.3</pVal> </Value> <Value> <xVal1>-70</xVal1> <xVal2>-78</xVal2> <pVal>0.7</pVal> </Value> </Door> </Round></Game>\[/code\]I have two \[code\]Doors\[/code\] for each \[code\]Round\[/code\] , then the question is , using \[code\]Dom\[/code\] or \[code\]Sax\[/code\] (or Jdom if it helps) can I iterate on my tree and get the data in every level ?At the moment I "went" a level down and got the Rounds , here : \[code\] DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse (new File("input.xml")); // normalize text representation doc.getDocumentElement ().normalize (); System.out.println ("Root element of the doc is " + // would produce Game doc.getDocumentElement().getNodeName()); NodeList roundNodes = doc.getElementsByTagName("Round"); // roundNodes are the Rounds int totalNodes = roundNodes.getLength(); // 2 by the example System.out.println("Total number of Rounds are : " + totalNodes); for (int i = 0; i < roundNodes.getLength() ; i++) { Node node = roundNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element)node; NodeList firstDoorList = element.getElementsByTagName("Door"); Element firstDoorElement = (Element)firstDoorList.item(0); NodeList textFNList = firstDoorElement.getChildNodes(); System.out.println("First Door : " + ((Node)textFNList.item(0)).getNodeValue().trim()); } }\[/code\]but it seems a lot of code for iteration .Is there a simple way to extract the data of that XML ? assume that I have 2 Doors per round and someK number of Rounds . Thanks
 
Back
Top