XML Parsing and deserialization

╄→гoц情女王★ 提交于 2019-12-17 20:27:23

问题


I have a xml file which Im reading it from my class

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

so i have a method in the class which takes an argument as an object as 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 created, which we are reading from the xml. Can i know how to parse the xml values from the file as an object and store it in the list? I just want to use list of all the class objects in my project and send them to this test class. later even if any new classes get added to the project i should be able to add to this xml file and pass the class object to this test.


回答1:


You may want to use simple Java Libraries such as XStream, which is very simple to use. All you need to define a POJO class to hold the parse values from XML and then use the library to parse the XML and produce 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 have a look at its two minutes tutorial.




回答2:


its something like that 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");          


来源:https://stackoverflow.com/questions/13731322/xml-parsing-and-deserialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!