使用Java原生的javax.xml.bind包下的JAXBContext将一个Xml文件中的数据映射到一个JavaBean中
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.InputStream; 5 6 import javax.xml.bind.JAXBContext; 7 import javax.xml.bind.JAXBException; 8 import javax.xml.bind.Unmarshaller; 9 10 public class ReadXML { 11 public static void readXmlToObject() { 12 try { 13 JAXBContext context = JAXBContext.newInstance(Object.class);// Object为Xml所映射的类 14 Unmarshaller unmar = context.createUnmarshaller(); 15 File file = new File("filePath");// filePath为xml的路径 16 InputStream input = new FileInputStream(file); 17 //InputStream input=ReadXML.class.getResourceAsStream("filePath"); 18 Object object = unmar.unmarshal(input);// 将Xml中的数据映射到object中 19 } catch (JAXBException e) { 20 e.printStackTrace(); 21 } catch (FileNotFoundException e) { 22 e.printStackTrace(); 23 } 24 } 25 }