java对象转xml报文
时间: 2023-10-09 19:08:48 浏览: 91
Java对象转XML报文可以使用Java内置的JAXB库来实现。首先定义一个Java类,使用注解标注类和属性的映射关系,然后使用JAXB提供的Marshaller类将Java对象转换为XML格式的报文。下面是一个示例代码:
```java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
public class Main {
public static void main(String[] args) throws JAXBException {
// 创建Java对象
Person person = new Person();
person.setName("张三");
person.setAge(18);
// 使用JAXB将Java对象转换为XML格式的报文
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(person, writer);
System.out.println(writer.toString());
}
}
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
private String name;
private int age;
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;
}
}
```
输出结果为:
```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<age>18</age>
<name>张三</name>
</person>
```
阅读全文