[英]How to return a XML file using JAXB
我有一项学校作业,我需要使用 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 文档来为我的工作找到答案,但我没有任何成功。
If you want to build a Java object in an XML string, obtain an instance of the JAXBContext class, for the use of the JAXB AP I since it provides methods to disarm, sort and validate operations. 然后获取JAXBContext的 Marshaller 实例。 The marshal() , method generates the Java object in XML, and then the XML object can be written to any ways. 例如:
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();
}
}
}
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<title>Everyday Italian</title>
<year>2005</year>
</book>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.