예제 #1
0
 /** 创建UnMarshaller. 线程不安全,需要每次创建或pooling。 */
 public static Unmarshaller createUnmarshaller(Class clazz) {
   try {
     JAXBContext jaxbContext = getJaxbContext(clazz);
     return jaxbContext.createUnmarshaller();
   } catch (JAXBException e) {
     throw Exceptions.unchecked(e);
   }
 }
예제 #2
0
 /** Xml->Java Object. */
 @SuppressWarnings("unchecked")
 public static <T> T fromXml(String xml, Class<T> clazz) {
   try {
     StringReader reader = new StringReader(xml);
     return (T) createUnmarshaller(clazz).unmarshal(reader);
   } catch (JAXBException e) {
     throw Exceptions.unchecked(e);
   }
 }
예제 #3
0
 /** Java Object->Xml with encoding. */
 public static String toXml(Object root, Class clazz, String encoding) {
   try {
     StringWriter writer = new StringWriter();
     createMarshaller(clazz, encoding).marshal(root, writer);
     return writer.toString();
   } catch (JAXBException e) {
     throw Exceptions.unchecked(e);
   }
 }
예제 #4
0
  /** Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形. */
  public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
    try {
      CollectionWrapper wrapper = new CollectionWrapper();
      wrapper.collection = root;

      JAXBElement<CollectionWrapper> wrapperElement =
          new JAXBElement<CollectionWrapper>(new QName(rootName), CollectionWrapper.class, wrapper);

      StringWriter writer = new StringWriter();
      createMarshaller(clazz, encoding).marshal(wrapperElement, writer);

      return writer.toString();
    } catch (JAXBException e) {
      throw Exceptions.unchecked(e);
    }
  }
예제 #5
0
  /** 创建Marshaller并设定encoding(可为null). 线程不安全,需要每次创建或pooling。 */
  public static Marshaller createMarshaller(Class clazz, String encoding) {
    try {
      JAXBContext jaxbContext = getJaxbContext(clazz);

      Marshaller marshaller = jaxbContext.createMarshaller();

      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

      if (StringUtils.isNotBlank(encoding)) {
        marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
      }

      return marshaller;
    } catch (JAXBException e) {
      throw Exceptions.unchecked(e);
    }
  }