将POJO转化成符合XML格式的字符串http://my.oschina.net/jeffli1993/blog/376846
时间: 2023-10-04 18:11:14 浏览: 83
可以使用Java自带的JAXB库来将POJO转化成符合XML格式的字符串。
首先,需要在POJO类上添加JAXB注解,例如:
```java
@XmlRootElement
public class User {
private String name;
private int age;
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
然后,可以使用JAXBContext和Marshaller将POJO转化成XML格式的字符串:
```java
public static String convertToXml(Object obj) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
}
```
调用方式如下:
```java
User user = new User("Tom", 30);
String xml = convertToXml(user);
System.out.println(xml);
```
输出结果如下:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<age>30</age>
<name>Tom</name>
</user>
```
注意:需要添加以下依赖:
```xml
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
```
阅读全文