您好,登錄后才能下訂單哦!
java中怎么將xml轉換成對象,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
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 static <T> T 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> 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轉換成對象的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。