Advertisement
Guest User

XMLParser

a guest
Mar 30th, 2020
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. package com.bulpros.javaknigths;
  2.  
  3. import javax.xml.bind.JAXBContext;
  4. import javax.xml.bind.JAXBException;
  5. import javax.xml.bind.Unmarshaller;
  6. import java.io.StringReader;
  7. import java.io.StringWriter;
  8.  
  9. public class XMLParser<T> implements Marshaller<T> {
  10.  
  11.     private Class<T> type;
  12.  
  13.     public XMLParser(Class<T> type){
  14.         this.type = type;
  15.     }
  16.  
  17.     @Override
  18.     public T read(String text) {
  19.         T item = null;
  20.         try {
  21.             JAXBContext context = JAXBContext.newInstance(type);
  22.             Unmarshaller unmarshaller = context.createUnmarshaller();
  23.             StringReader reader = new StringReader(text);
  24.             item = (T) unmarshaller.unmarshal(reader);
  25.         } catch (JAXBException e) {
  26.             e.printStackTrace();
  27.         }
  28.         return item;    }
  29.  
  30.     @Override
  31.     public String write(T item) {
  32.         StringWriter writenXml = new StringWriter();
  33.         try {
  34.             JAXBContext context = JAXBContext.newInstance(type);
  35.             javax.xml.bind.Marshaller marshaller = context.createMarshaller();
  36.             marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  37.             marshaller.marshal(item, writenXml);
  38.         } catch (JAXBException e) {
  39.             e.printStackTrace();
  40.         }
  41.         return writenXml.toString();
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement