XMLTranslator.java import javax.xml.bind.JAXBContext;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;import java.io.*;/** * 基于JAXB规范的XML解析器。 * 使用此工具需要针对DOM结构生成带有JAXB注解的
import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.*; /** * 基于JAXB规范的XML解析器。 * 使用此工具需要针对DOM结构生成带有JAXB注解的实体,可以使用工具生成(trang.jar),见以下描述: * * 1. 准备XML文件,为其生成XSD文档 * (java -jar trang.jar test.xml test.xsd) * * 2. 使用生成的xsd文件构建JavaBean文件 * (xjc test.xsd -d E:/xmlbean -p com.fastjee.model.xml) * (xjc xsd文件 -d 实体保存路径 -p 包名) */ public class XMLTranslator { private XMLTranslator() {} /** * 将符合jaxb规范的JavaBean转换为xml字符串 * * @param obj * @param format 格式化输出 * @return XML字符串 */ public static String pojo2xml(Object obj, boolean format) { required(obj); try (Writer writer = new StringWriter()) { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); if (format) { // 格式化xml输出的格式 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); } // 将对象转换成输出流形式的xml marshaller.marshal(obj, writer); return writer.toString().replace("standalone=\"yes\"", ""); } catch (Exception e) { throw new RuntimeException("pojo2xml:转换失败," + e.getMessage()); } } /** * @see #pojo2xml(Object, boolean) */ public static String pojo2xml(Object obj) { return pojo2xml(obj, true); } /** * 将符合jaxb规范的JavaBean转换为xml文件 * * @param obj * @param filePath 文件全路径 * @param format 格式化 * @return XML文件对象 */ public static File pojo2file(Object obj, String filePath, boolean format) { required(obj, filePath); File file = new File(filePath); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try (Writer writer = new FileWriter(file)) { writer.write(pojo2xml(obj, format)); writer.flush(); } catch (Exception e) { e.printStackTrace(); } return file; } /** * @see #pojo2file(Object, String, boolean) */ public static File pojo2file(Object obj, String filePath) { return pojo2file(obj, filePath, true); } /** * XML文件转JavaBean */ public staticT file2pojo(Class clazz, File file) { return toPojo(clazz,file); } /** * XML字符串转JavaBean */ public static T xml2pojo(Class clazz, String xml) { return toPojo(clazz, xml); } private static T toPojo(Class clazz, Object obj) { required(clazz,obj); try (Reader reader = (obj instanceof String) ? new StringReader((String) obj) : new FileReader((File) obj)) { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = context.createUnmarshaller(); return (T) unmarshaller.unmarshal(reader); } catch (Exception e) { throw new RuntimeException("toPojo:转换失败," + e.getMessage()); } } private static void required(Object... obj) { for (int i = 0; i < obj.length; i++) { if (null == obj[i]) throw new IllegalArgumentException("参数[" + i + "]不能为空。"); } } }