본문 바로가기
TIL/Java

Marshalling and Unmarshalling by the JAXB

by DandyU 2016. 11. 15.

JAXB로 마샬링과 언마샬링 하려면 JAXB 클래스가 있어야 함

JAXB 클래스는 .xsd라고 XML 스키마가 정의된 파일을 xjc 툴로 자동 생성함

(.xsd 파일은 어디선가 받겠죠~!)

.xsd가 있는 경로에서 "xjc -d . *"를 실행하면 JAXB 클래스가 생성됨, 좀더 디테일한 설정은 Help 참조

(xjc -d . * -p com.company.sub)

마샤링과 언마샬링은 아래 소스 코드 참고


 public class JaxbConvertor {

private static JaxbConvertor mSingleton = null;

private JAXBContext mJAXBContext = null;


private JaxbConvertor()

throws JAXBException {

mJAXBContext = JAXBContext.newInstance(

JAXB1.class,

JAXB2.class,

                                ... // xjc 툴로 생성한 JAXB 클래스 입력 1..N 개 

); // JAXBContext 생성 작업은 비용이 크기 때문에 싱글턴 패턴 적용

}


public static JaxbConvertor getInstance()

throws JAXBException {

if (mSingleton == null)

mSingleton = new JaxbConvertor();

return mSingleton;

}


public void objectToStream(Object object, OutputStream outputStream)

throws JAXBException {

Marshaller marshaller = mJAXBContext.createMarshaller();

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

marshaller.marshal(object, outputStream);

}


public Object streamToObject(InputStream inputStream)

throws JAXBException {

Unmarshaller unmarshaller = mJAXBContext.createUnmarshaller();

return unmarshaller.unmarshal(inputStream);

}


public String objectToString(Object object)

throws JAXBException {

StringWriter stringWriter = new StringWriter();

Marshaller marshaller = mJAXBContext.createMarshaller();

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

marshaller.marshal(object, stringWriter);

return stringWriter.toString();

}


public Object stringToObject(String string)

throws XMLStreamException, FactoryConfigurationError, JAXBException {

XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(string));

Unmarshaller unmarshaller = mJAXBContext.createUnmarshaller();

return unmarshaller.unmarshal(reader);

}


public Document objectToDom(Object object)

throws ParserConfigurationException, JAXBException {

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

Document doc = dBuilder.newDocument();

Marshaller marshaller = mJAXBContext.createMarshaller();

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

marshaller.marshal(object, doc);

return doc;

}

}


추가로 생성한 XML 데이터 검증 방법은 아래와 같음

스키마를 만족하지 않는 경우 Exception 발생


public class JaxbValidator {

public static boolean validate(String xsdFilePath, String xmlFilePath) {

try {

            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            Schema schema = factory.newSchema(new File(xsdFilePath));

            Validator validator = schema.newValidator();

            validator.validate(new StreamSource(new File(xmlFilePath)));

        } catch (IOException | SAXException e) {

            System.out.println("Exception: "+e.getMessage());

            return false;

        }

        return true;

}

}


'TIL > Java' 카테고리의 다른 글

GSON Type 정의 관련 정리  (0) 2017.11.21
injecting XML(Document) into SOAP body(SOAPBody)  (0) 2016.11.15
Convert date(String) to XMLGregorianCalendar  (0) 2016.11.15

댓글