java 读取xml 文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaofanren1111/article/details/82734016


xml 与对象之间的映射
@XmlRootElement(name = "d")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlAttribute(name = "d1")
xml 与 对象列表的映射
@XmlRootElement(name = "c")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlElement(name = "d")
xml转为指定的java 对象
public static Object xmlStrToOject(Class<?> clazz, String xmlStr) throws Exception {
   Object xmlObject = null;
   Reader reader = null;
   JAXBContext context = JAXBContext.newInstance(clazz);
   
   // XML 转为对象的接口
   Unmarshaller unmarshaller = context.createUnmarshaller();
   
   reader = new StringReader(xmlStr);
   xmlObject = unmarshaller.unmarshal(reader);
   
   if (null != reader) {
      reader.close();
   }
   
   return xmlObject;
}
读取xml 并转化响应的对象
Resource resource = new ClassPathResource("xxx.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), "utf-8"));
StringBuffer buffer = new StringBuffer();
String line = "";

while ((line = br.readLine()) !=null) {
   buffer.append(line);
}

br.close();

// XML转为Java对象
XxxX xxxX= (XxxX )XmlBuilder.xmlStrToOject(xxxX.class, buffer.toString());

猜你喜欢

转载自blog.csdn.net/xiaofanren1111/article/details/82734016