JAXB: Deserializing an xml string for unit tests

Sometimes it is useful to take a copy of an xml to help setup data for unit tests. The following is a snippet you could use


        String rsXml = "    <SampleResponse xmlns=\"http://magicmonster.com/sample/\">\n" +
                "      <header>\n" +
                "        <version>2.3</version>\n" +
                "      </header>\n" +
                "      <body>\n" +
                "        <transactionStatus code=\"08\">\n" +
                "        </transactionStatus>\n" +
                "      </body>\n" +
                "    </SampleResponse>";
        JAXBContext jaxbContext = JAXBContext.newInstance(SampleResponse.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        SampleResponse response = (SampleResponse) unmarshaller.unmarshal(new ByteArrayInputStream(rsXml.getBytes()));
  

It is assumed you have already generated jaxb java classes from the xsd.

Published: Monday, 26 July 2010