問題描述
我有一個(gè) xml 文件,我從課堂上讀取它
I have a xml file which Im reading it from my class
<Testclasses>
<Class>new SomeClass1()</class>
<class>new SomeClass2()</class>
</Testclasses>
所以我在類中有一個(gè)方法,它將參數(shù)作為對(duì)象,如下所示
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){
.....
}
其中 target 是創(chuàng)建的新 SomeClass() 對(duì)象,我們從 xml 中讀取該對(duì)象.我可以知道如何將文件中的 xml 值解析為對(duì)象并將其存儲(chǔ)在列表中嗎?我只想使用我項(xiàng)目中所有類對(duì)象的列表并將它們發(fā)送到這個(gè)測(cè)試類.以后即使任何新類被添加到項(xiàng)目中,我也應(yīng)該能夠添加到這個(gè) xml 文件并將類對(duì)象傳遞給這個(gè)測(cè)試.
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.
推薦答案
您可能想要使用簡(jiǎn)單的 Java 庫(kù),例如 XStream,使用起來非常簡(jiǎn)單.您只需要定義一個(gè) POJO 類來保存來自 XML 的解析值,然后使用該庫(kù)來解析 XML 并為您生成轉(zhuǎn)換后的 java 對(duì)象.
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);
請(qǐng)看一下它的兩分鐘教程.
Please have a look at its two minutes tutorial.
這篇關(guān)于XML 解析和反序列化的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!