在这个代码片段中,您可以学习如何将XML文件转换或反汇编为相应的POJO。将XML解组到对象的步骤从创建JAXBContext实例开始。使用context对象,我们可以创建Unmarshaller类的实例。使用unmarshall()方法并传递一个XML文件,将得到目标POJO作为结果。
让我们看看下面的代码片段:
package org.nhooo.example.jaxb; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; public class JAXBXmlToObject { public static void main(String[] args) { try { File file = new File("Track.xml"); JAXBContext context = JAXBContext.newInstance(Track.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Track track = (Track) unmarshaller.unmarshal(file); System.out.println("Track = " + track); } catch (JAXBException e) { e.printStackTrace(); } } }
这是上下文Track.xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <track id="2"> <title>She Loves You</title> </track>