XML Parsing and deserialization(XML 解析和反序列化)
问题描述
我有一个 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 解析和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:XML 解析和反序列化
- 获取数字的最后一位 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01