java实体类转xml
时间: 2023-10-09 13:08:49 浏览: 48
Java中可以使用JAXB(Java Architecture for XML Binding)库将实体类转换为XML,JAXB提供了将Java对象和XML文档相互转换的能力。
以下是一个示例代码,将Book类转换为XML格式:
```java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.StringWriter;
@XmlRootElement
public class Book {
private String title;
private String author;
private int year;
private float price;
public Book() {}
public Book(String title, String author, int year, float price) {
this.title = title;
this.author = author;
this.year = year;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public static void main(String[] args) throws Exception {
Book book = new Book("Java Programming", "John Smith", 2021, 29.99f);
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(book, writer);
System.out.println(writer.toString());
}
}
```
输出结果为:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<author>John Smith</author>
<price>29.99</price>
<title>Java Programming</title>
<year>2021</year>
</book>
```
在上面的代码中,我们使用了JAXBContext.newInstance()方法来创建一个JAXBContext对象,然后使用createMarshaller()方法创建Marshaller对象,最后调用marshal()方法将Java对象转换为XML格式,并将结果输出到字符串中。在Book类上使用了@XmlRootElement注解,这个注解用来指定生成XML文件的根元素名称。