使用JAXB将Java对象与XML相互转换

XML绑定的Java体系结构(JAXB)是将Java对象映射到XML以及从XML映射Java对象的流行选择。它提供了易于使用的编程接口,用于将Java对象读取和写入XML,反之亦然。

在此快速指南中,您将学习如何将Java对象转换为XML文档。我们还将看一个将XML文档转换回Java对象的示例。

依存关系

Java 1.6以来,JAXBJava开发工具包(JDK)的一部分。因此,您不需要任何第三方依赖就可以在项目中使用JAXB

编组— Java对象到XML

JAXB术语中,Java对象到XML的转换称为封送处理。编组将Java对象转换为XML文档的过程。JAXB提供了Marshall执行此转换的类。

创建Java

在我们实际讨论封送处理的工作原理之前,让我们首先创建两个简单的Java类,分别称为AuthorBook。这些类为一个非常简单的场景建模,在这种场景中,我们有一本书,而每一本书恰好有一位作者。

我们首先创建Author类以对作者进行建模:

public class Author {

	private Long id;
	private String firstName;
	private String lastName;

	public Author() {
	}

	public Author(Long id, String firstName, String lastName) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "Author{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}';
	}
}

Author 是一个简单的Java类,具有ID,名字和姓氏以及它们相应的getsetter方法。

接下来,我们将创建Book该类并使用JAXB批注注释其字段,以控制应如何将其编组为XML

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "book")
public class Book {

	private Long id;
	private String title;
	private String isbn;
	private Author author;

	public Book() {
	}

	public Book(Long id, String title, String isbn, Author author) {
		this.id = id;
		this.title = title;
		this.isbn = isbn;
		this.author = author;
	}

	public Long getId() {
		return id;
	}

	@XmlAttribute(name = "id")
	public void setId(Long id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	@XmlElement(name = "title")
	public void setTitle(String title) {
		this.title = title;
	}

	public String getIsbn() {
		return isbn;
	}

	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

	public Author getAuthor() {
		return author;
	}

	@XmlElement(name = "author")
	public void setAuthor(Author author) {
		this.author = author;
	}

	@Override
	public String toString() {
		return "Book{" + "id=" + id + ", title='" + title + '\'' + ", isbn='" + isbn + '\'' + ", author=" + author
				+ '}';
	}
}

 

Book上面的类中,我们使用了几个JAXB注释:

  • @XmlRootElement—在顶级类中使用此批注指定XML文档的根元素。批注中的name属性是可选的。如果未指定,则将类名用作XML文档中根元素的名称。
  • @XmlAttribute —此注释用于指示根元素的属性。
  • @XmlElement —在将作为根元素的子元素的类的字段上使用此注释。

而已。Book现在可以将类编组到XML文档中。让我们从一个简单的场景开始,您要将Java对象转换为XML字符串。

Java对象转换为XML字符串

要将Java对象转换为XML字符串,您需要首先创建的实例JAXBContext。这是JAXB API的切入点,它提供了封送,取消封送和验证XML文档的几种方法。

接下来,Marshall从获取实例JAXBContext。之后,使用其marshal()方法将Java对象编组为XML。您可以将生成的XML写入文件,字符串,或仅在控制台上将其打印。

这是将Book对象转换为XML字符串的示例:

try {

    // create an instance of `JAXBContext`

    JAXBContext context = JAXBContext.newInstance(Book.class);

 

    // create an instance of `Marshaller`

    Marshaller marshaller = context.createMarshaller();

 

    // enable pretty-print XML output

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

 

    // write XML to `StringWriter`

    StringWriter sw = new StringWriter();

 

    // create `Book` object

    Book book = new Book(17L, "Head First Java", "ISBN-45565-45",

            new Author(5L, "Bert", "Bates"));

 

    // convert book object to XML

    marshaller.marshal(book, sw);

 

    // print the XML

    System.out.println(sw.toString());

 

} catch (JAXBException ex) {

    ex.printStackTrace();

}

上面的代码将在控制台上打印以下内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<book id="17">

    <author>

        <firstName>Bert</firstName>

        <id>5</id>

        <lastName>Bates</lastName>

    </author>

    <isbn>ISBN-45565-45</isbn>

    <title>Head First Java</title>

</book>

Java对象转换为XML文件

Java对象到XML文件的转换与上面的示例非常相似。您需要做的只是将StringWriter实例替换为File要存储XML的实例:

try {

    // create an instance of `JAXBContext`

    JAXBContext context = JAXBContext.newInstance(Book.class);

 

    // create an instance of `Marshaller`

    Marshaller marshaller = context.createMarshaller();

 

    // enable pretty-print XML output

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

 

    // create XML file

    File file = new File("book.xml");

 

    // create `Book` object

    Book book = new Book(17L, "Head First Java", "ISBN-45565-45",

            new Author(5L, "Bert", "Bates"));

 

    // convert book object to XML file

    marshaller.marshal(book, file);

 

} catch (JAXBException ex) {

    ex.printStackTrace();

}

现在,如果您执行上述代码片段,您将看到一个名为XMLXML文件book.xml,其生成的XML内容与上述示例相同。

解组— XMLJava对象

XMLJava对象的转换或解组涉及Unmarshaller从创建一个实例JAXBContext并调用unmarshal()方法。此方法接受XML文件作为解组参数。

以下示例显示了如何将book.xml上面刚刚创建的文件转换为的实例Book

try {

    // create an instance of `JAXBContext`

    JAXBContext context = JAXBContext.newInstance(Book.class);

 

    // create an instance of `Unmarshaller`

    Unmarshaller unmarshaller = context.createUnmarshaller();

 

    // XML file path

    File file = new File("book.xml");

 

    // convert XML file to `Book` object

    Book book = (Book) unmarshaller.unmarshal(file);

 

    // print book object

    System.out.println(book);

 

} catch (JAXBException ex) {

    ex.printStackTrace();

}

这是上面示例的输出:

Book{id=17, title='Head First Java', isbn='ISBN-45565-45', author=Author{id=5, firstName='Bert', lastName='Bates'}}

马歇尔Java集合到XML

很多时候,您想将Java集合对象(例如ListMap)或SetXML文档编组,还希望将XML转换回Java集合对象。

对于这样的情况下,我们需要创建一个名为一类特殊的Books是持有ListBook对象。看起来是这样的:

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "books")
public class Books {

	private List<Book> books;

	public List<Book> getBooks() {
		return books;
	}

	@XmlElement(name = "book")
	public void setBooks(List<Book> books) {
		this.books = books;
	}

	public void add(Book book) {
		if (this.books == null) {
			this.books = new ArrayList<>();
		}
		this.books.add(book);
	}
}

 

Books上面的类中,@XmlRootElement注释将XML的根元素表示为books。此类只有一个List具有gettersetter方法的字段。add()此类的方法接受一个Book对象并将其添加到列表中。

下面的示例演示如何Java集合对象转换为XML文档

try {

    // create an instance of `JAXBContext`

    JAXBContext context = JAXBContext.newInstance(Books.class);

 

    // create an instance of `Marshaller`

    Marshaller marshaller = context.createMarshaller();

 

    // enable pretty-print XML output

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

 

    // create `Books` object

    Books books = new Books();

 

    // add books to list

    books.add(new Book(1L, "Head First Java", "ISBN-45565-45",

            new Author(1L, "Bert", "Bates")));

    books.add(new Book(2L, "Thinking in Java", "ISBN-95855-3",

            new Author(2L, "Bruce", "Eckel")));

 

    // convert `Books` object to XML file

    marshaller.marshal(books, new File("books.xml"));

 

    // print XML to console

    marshaller.marshal(books, System.out);

 

} catch (JAXBException ex) {

    ex.printStackTrace();

}

上面的示例将以下XML输出到books.xml文件以及在控制台上:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<books>

    <book id="1">

        <author>

            <firstName>Bert</firstName>

            <id>1</id>

            <lastName>Bates</lastName>

        </author>

        <isbn>ISBN-45565-45</isbn>

        <title>Head First Java</title>

    </book>

    <book id="2">

        <author>

            <firstName>Bruce</firstName>

            <id>2</id>

            <lastName>Eckel</lastName>

        </author>

        <isbn>ISBN-95855-3</isbn>

        <title>Thinking in Java</title>

    </book>

</books>

结论

Java对象转换为XML文档,反之亦然。我们学习了如何将Java对象或Java集合对象编组为XML文件。同样,我们还看了一个将XML文档转换回Java对象的示例。

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java中的JAXBJava Architecture for XML Binding)库来将Java对象转换XML文件。 JAXB提供了将Java转换XML文档和从XML文档中读取Java类的机制。下面是一个示例代码片段: ``` import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; public class ObjectToXML { public static void main(String[] args) throws Exception { //创建需要转换XMLjava对象 Employee employee = new Employee(); employee.setId(1001); employee.setName("张三"); employee.setAge(25); //将Java对象转换XML文件 JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(employee, new File("employee.xml")); //将XML文件转换Java对象 Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Employee unmarshalledEmployee = (Employee) unmarshaller.unmarshal(new File("employee.xml")); System.out.println(unmarshalledEmployee.getId() + " " + unmarshalledEmployee.getName() + " " + unmarshalledEmployee.getAge()); } } ``` 该示例创建了一个名为Employee的Java类,具有id、name和age属性。然后使用JAXBContext创建了Marshaller和Unmarshaller,分别将Java对象转换XML并将XML转换Java对象。运行该示例后,将生成一个名为“employee.xml”的XML文件,并在控制台打印转换后的Java对象的属性值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值