对象转xml or xml转对象(XStream and jaxb)

前端之家收集整理的这篇文章主要介绍了对象转xml or xml转对象(XStream and jaxb)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

需要的jar包:xstream-1.4.2.jar

maven pom 依赖:

<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.2</version>
</dependency>

demo如下:

package com.csair.test.xstream;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.xml.StaxDriver;

/**
* test XStream
* @author ppt
*
*/
public class TestXStream {

public static void main(String[] args) {
Person person = new Person();
person.setId(1);
person.setPassword("ppt");
person.setUsername("pengpanting");
//XStream xStream = new XStream();
//XStream xStream = new XStream(new DomDriver());//dom解析xml
XStream xStream = new XStream(new StaxDriver());//stax解析xml
//xStream.alias("person",Person.class);
String str = xStream.toXML(person);
System.out.println(str);

Person per = (Person)xStream.fromXML(str);
System.out.println(per.toString());

}
}

@XStreamAlias("person")
class Person {
private int id;
private String username;
private String password;

@Override
public String toString() {
return "Person [id=" + id + ",username=" + username + ",password="
+ password + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

二、jaxb方式

<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>

/** * 对象转xml * @return * @throws Exception */ private static String getXml() throws Exception { UserDTO dto = new UserDTO(); dto.setId(12); dto.setPassword("ppt"); dto.setUsername("ppt"); JAXBContext jaxb = JAXBContext.newInstance(UserDTO.class); Marshaller marshaller = jaxb.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(dto,sw); return sw.toString(); } /** * xml转对象 * @param xml * @return * @throws Exception */ private static UserDTO getObject(String xml) throws Exception { JAXBContext jaxb = JAXBContext.newInstance(UserDTO.class); Unmarshaller unmarshaller = jaxb.createUnmarshaller(); UserDTO dto = (UserDTO)unmarshaller.unmarshal(new StringReader(xml)); return dto; }

猜你在找的XML相关文章