java中怎么将xml转换成对象
java中怎么将xml转换成对象,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
成都创新互联公司是一家集成都网站设计、网站建设、网站页面设计、网站优化SEO优化为一体的专业网络公司,已为成都等多地近百家企业提供网站建设服务。追求良好的浏览体验,以探求精品塑造与理念升华,设计最适合用户的网站页面。 合作只是第一步,服务才是根本,我们始终坚持讲诚信,负责任的原则,为您进行细心、贴心、认真的服务,与众多客户在蓬勃发展的市场环境中,互促共生。
package util; import lombok.extern.slf4j.Slf4j; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; import java.io.FileInputStream; import java.io.StringReader; import java.io.StringWriter; @Slf4j public class JaxbUtil { public static JAXBContext newInstance(Class obj) { JAXBContext jaxbContext = null; try { jaxbContext = JAXBContext.newInstance(obj); } catch (JAXBException e) { e.printStackTrace(); } return jaxbContext; } public static String convertToXml(Object obj) { return convertToXml(obj, "UTF-8"); } public static String convertToXml(Object obj, String encoding) { String result = null; try { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); StringWriter writer = new StringWriter(); marshaller.marshal(obj, writer); result = writer.toString(); } catch (Exception e) { log.error("convertToXml error", e); } return result; } public staticT converyToJavaBean(String xml, JAXBContext context) { T t = null; StringReader sr = null; try { sr = new StringReader(xml); Unmarshaller unmarshaller = context.createUnmarshaller(); t = (T) unmarshaller.unmarshal(sr); } catch (Exception e) { log.error("converyToJavaBean error", e); } finally { if (null != sr) { sr.close(); } } return t; } public static T xmlAnalyze(String path, JAXBContext jaxbContext, T t) { try { File file = new File(path); FileInputStream in = new FileInputStream(file); int size = in.available(); byte[] buffer = new byte[size]; in.read(buffer); in.close(); String xmlStr = new String(buffer, "utf-8"); t = JaxbUtil.converyToJavaBean(xmlStr, jaxbContext); } catch (Exception e) { log.error("xml解析失败" + t.getClass()); } return t; } // public static void main(String[] args) { // OutInfo outInfo = new OutInfo(); // outInfo = xmlAnalyze("C:\\Users\\yzhang\\Desktop\\inout_pedinfo_8_000026600.xml", newInstance(outInfo.getClass()), outInfo); // System.out.println(outInfo); // } }
看完上述内容,你们掌握java中怎么将xml转换成对象的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
新闻标题:java中怎么将xml转换成对象
分享网址:http://azwzsj.com/article/goicpg.html