SpringMVC读取XML数据

1.book_xml.xml 特别注意!XML标签名必须与模型数据类型一致,否则无法读取
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<bookXml>
<id>1</id>
<name>我是书名</name>
<author>我是作者</author>
</bookXml>

2.视图

$(function(){
    init_list();
});
function init_list()
{
    $.ajax({
        type: "POST",
        contentType:'application/xml;charset=UTF-8',
        cache: false,
        url: "${pageContext.request.contextPath}/interface/xml2bookv2",
        success: function (message) {
            console.log(message);
        },
        error: function (message) {
            console.log(message);
        }
    });
}

3.控制器

@RequestMapping("/interface/xml2bookv2")
public @ResponseBody Book_xml xml2bookv2() throws Exception
{
    //通过JAXBCpntext的newInstance方法,传递一个class就可以获得一个上下文
    JAXBContext context = JAXBContext.newInstance(Book_xml.class);
    //创建一个Unmarshall对象
    Unmarshaller unmar = context.createUnmarshaller();
    InputStream is = this.getClass().getResourceAsStream("book_xml.xml");
    //Unmarshall对象的unmarshal方法可以进行xml到java对象的转换
    Book_xml book_xml = (Book_xml)unmar.unmarshal(is);
    return book_xml;
}