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 解析和反序列化
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01