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

查看:179
本文介绍了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);

请查看其 两分钟教程

这篇关于XML解析和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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