XML parsing and deserialization

I have an xml file that Im reading from my class

<Testclasses> <Class>new SomeClass1()</class> <class>new SomeClass2()</class> </Testclasses> 

so I have a method in the class that takes an argument as an object as shown below

 public List<Object> retriveValuesFromXml(){ .... This method parses the values from xml and reads the different object and returns a list of objects. } @Test public void someMethod1(){ ArrayList<Object> list_of_objects= retriveValuesFromXml(); for(Object x :list_of_objects){ someMethod2(x); //for example : x = new SomeClass1() or x = new SomeClass2() } } public void someMethod2(Object target){ ..... } 

where target is the new SomeClass () object we are reading from xml. Can I know how to parse the xml values ​​from a file as an object and store it in a list? I just want to use a list of all the class objects in my project and send them to this test class. later, even if any new classes are added to the project, I should be able to add to this xml file and pass the class object to this test.

+4
source share
2 answers

You might want to use simple Java libraries like XStream , which is very easy to use. All you need is to define a POJO class to store parsing values ​​from XML, and then use the library to parse the XML and create the converted Java objects for you.

  XStream xstream = new XStream(); //converting object to XML String xml = xstream.toXML(myObject); //converting xml to object MyClass myObject = (MyClass)xstream.fromXML(xml); 

Please review the tutorial for two minutes .

+6
source

something like this i imagine

 DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse("name_of_file.xml"); Element rootElement = doc.getDocumentElement(); NodeList nl=rootElement.getElementsByTagName("TestClass"); 
+3
source

All Articles