我有一项学校作业,需要使用 JAXB 框架返回计算机上文件夹中的 xml。我需要返回的 XML 文件夹如下,我必须使用 java 语言来完成。
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
相信我,我试图通过观看大量教程和官方 Oracle 文档来为我的工作找到答案,但我没有取得任何成功。
最佳答案
如果您想在 XML 字符串中构建 Java 对象,请获取 JAXBContext 类的实例,以供 JAXB API 使用,因为它提供了方法撤防、排序和验证操作。然后获取JAXBContext的Marshaller实例。 marshal(),方法生成XML中的Java对象,然后可以将XML对象写入任何方式。例如:
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBTest {
public static void main(String[] args) {
Book book = new Book("Everyday Italian", 2005);
generateXML(book);
}
private static final void generateXML(Book book) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter stringWriter = new StringWriter();
marshaller.marshal(book, stringWriter);
System.out.println(stringWriter.toString());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<title>Everyday Italian</title>
<year>2005</year>
</book>
关于java - 如何使用 JAXB 返回 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58867385/