xstream fromxml
时间: 2023-07-29 20:09:56 浏览: 117
XStream
is a Java library that allows you to serialize Java objects to XML and deserialize XML back to Java objects. It provides a simple API for converting object hierarchies to XML and vice versa.
To deserialize XML to an object using XStream, you can use the fromXML
method. Here's an example:
import com.thoughtworks.xstream.XStream;
public class Main {
public static void main(String[] args) {
// Create an instance of XStream
XStream xstream = new XStream();
// Deserialize XML to an object
String xml = "<person><name>John Doe</name><age>30</age></person>";
Person person = (Person) xstream.fromXML(xml);
// Print the deserialized object
System.out.println(person.getName()); // Output: John Doe
System.out.println(person.getAge()); // Output: 30
}
}
class Person {
private String name;
private int age;
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
In this example, we create an instance of XStream
and then use the fromXML
method to deserialize the XML string to a Person
object. Finally, we access the properties of the deserialized object.
Note that you need to have the XStream library in your classpath to use it in your project. You can add it as a dependency using a build tool like Maven or Gradle.
相关推荐















