Read data from XML file (in Java) using Reflection

moorejungle

New Member
Given a simple XML file , like : \[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 want to read data from that file . I can do it in the old fashioned way of reading the tags , and create the objects accordingly , but I want to do it using Reflection mechanism . Can someone please explain or direct me to a tutorial that can explain how to do that ? Thanks EDIT:I did the following : \[code\]import java.io.File;import org.w3c.dom.Document;import org.w3c.dom.*;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.DocumentBuilder;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException; public class ReadAndPrintXMLFile { public static void main (String argv []){ try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse (new File("input.xml")); // ROOT // normalize text representation doc.getDocumentElement ().normalize (); System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName()); // Number of nodes/rounds NodeList listOfItems = doc.getElementsByTagName("Round"); int totalElements = listOfItems.getLength(); System.out.println("Total number of nodes : " + totalElements );......}\[/code\]This is a partial code , I ran the code and tested it , and at the moment , using SAX , I can read from the XML file above .Now , what I want to do is to manipulate the data using Reflection . From my understanding Reflection works only with EXISTING objects . Hence , is it enough to store the data (I.E. the rounds) in the variable \[code\]listOfItems\[/code\] and now use Reflection on that ? thanks again !
 
Back
Top