XML 解析和反序列化 [英] XML Parsing and deserialization

查看:21
本文介绍了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 解析和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆