1.创建Java类并使用JAXB注解
java
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
@XmlRootElement
public class Customer {
private String name;
private int age;
// JAXB要求有一个无参构造函数
public Customer() {
}
// 构造函数、getter和setter略
@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;
}
}
2.将Java对象转换为XML字符串
java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
public class JAXBExample {
public static void main(String[] args) throws Exception {
Customer customer = new Customer();
customer.setName("John Doe");
customer.setAge(30);
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(customer, writer);
String xmlString = writer.toString();
System.out.println(xmlString);
}
}