Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

java - XML Parsing and deserialization

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...