java XML 解析和反序列化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13731322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XML Parsing and deserialization
提问by iuser
I have a xml file which Im reading it from my class
我有一个 xml 文件,我从我的班级中读取它
<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){
.....
}
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.
其中 target 是创建的新 SomeClass() 对象,我们正在从 xml 中读取该对象。我可以知道如何将文件中的 xml 值解析为对象并将其存储在列表中吗?我只想使用我项目中所有类对象的列表并将它们发送到这个测试类。稍后,即使将任何新类添加到项目中,我也应该能够添加到此 xml 文件并将类对象传递给此测试。
回答by Yogendra Singh
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.
您可能想要使用简单的 Java 库,例如XStream,它使用起来非常简单。您只需要定义一个 POJO 类来保存来自 XML 的解析值,然后使用该库来解析 XML 并为您生成转换后的 java 对象。
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.
请看一看它的两分钟教程。
回答by Mamadou
its something like that i imagine
它就像我想象的那样
DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = db.parse("name_of_file.xml");
Element rootElement = doc.getDocumentElement();
NodeList nl=rootElement.getElementsByTagName("TestClass");