問題描述
我有一個 xml 文件,我從課堂上讀取它
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){
.....
}
其中 target 是創建的新 SomeClass() 對象,我們從 xml 中讀取該對象.我可以知道如何將文件中的 xml 值解析為對象并將其存儲在列表中嗎?我只想使用我項目中所有類對象的列表并將它們發送到這個測試類.以后即使任何新類被添加到項目中,我也應該能夠添加到這個 xml 文件并將類對象傳遞給這個測試.
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.
推薦答案
您可能想要使用簡單的 Java 庫,例如 XStream,使用起來非常簡單.您只需要定義一個 POJO 類來保存來自 XML 的解析值,然后使用該庫來解析 XML 并為您生成轉換后的 java 對象.
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.
這篇關于XML 解析和反序列化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!