JiBX Marshall to XML and back
February 18, 2010
The JiBX project is a very quick way of converting from XML to Java Objects and back.
Marshall Object to XML
Here's the code that will take an object, appropriately compiled with JiBX bindings, and convert it into XML in a String. This method assumes that it is on the object to be marshalled.
String lXml = null; try { IBindingFactory lBindingFactory = BindingDirectory.getFactory(JavaClassWithBindings.class); IMarshallingContext lContext = lBindingFactory.createMarshallingContext(); ByteArrayOutputStream lOutputStream = new ByteArrayOutputStream(); lContext.marshalDocument(pObjectToMarshall, "UTF-8", null, lOutputStream); lXml = new String(lOutputStream.toByteArray(), "UTF-8"); } catch (JiBXException lEx) { throw new RuntimeException("Problems generating XML, underlying problem is " + lEx.getMessage(), lEx); } catch (UnsupportedEncodingException lEx) { throw new RuntimeException("Problems generating XML in specified encoding, underlying problem is " + lEx.getMessage(), lEx); }
Unmarshall XML to Object
This code goes the other way and converts XML into Java Objects.
JavaClassWithBindings lParam = null; try { IBindingFactory lBindingFactory = BindingDirectory.getFactory(JavaClassWithBindings.class); IUnmarshallingContext lUnmarshallingContext = lBindingFactory.createUnmarshallingContext(); lParam = (JavaClassWithBindings) lUnmarshallingContext.unmarshalDocument(new StringReader(lXmlToProcess)); } catch (JiBXException lEx) { throw new RuntimeException("Problems parsing XML, underlying problem is " + lEx.getMessage(), lEx); }