Creating SAML Objects from an XML Source

Creating SAML objects from an XML source is done through a process known as unmarshalling which operates on DOM Elements. The OpenSAML 2 library contains many unmarshallers and the appropriate one is selected based off of either the XML Schema type of the Element to be unmarshalled or the Element's QName (a tuple representing the namespace the element is in and the element's name).

Unmarshalling Basics

  1. Parse the XML into a DOM element.
  2. Retrieve the unmarshaller factory using org.opensaml.Configuration#getUnmarshallerFactory()
  3. Get an unmarshaller for the element using the org.opensaml.xml.io.UnmarshallerFactory#getUnmarshaller(Element) method. The element argument is the root element from which you wish to begin unmarshalling. This is normally the document element if you're unmarshalling data from a file.
  4. Invoke the unmarshall(Element) method on the returned Unmarshaller using the same element argument as in the previous step.

Unmarshalling Example

The following example shows the parsing and unmarshalling of a SAML 2 metadata document. The try/catch code has been omitted here for readability. The complete code can be found in org.opensaml.saml2.metadata.MetadataTest#testInCommonUnmarshall() method in the OpenSAML 2.0 test source code.

String inCommonMDFile = "/data/org/opensaml/saml2/metadata/InCommon-metadata.xml";

// Initialize the library
DefaultBootstrap.bootstrap(); 

// Get parser pool manager
BasicParserPool ppMgr = new BasicParserPool();
ppMgr.setNamespaceAware(true);

// Parse metadata file
InputStream in = MetadataTest.class.getResourceAsStream(inCommonMDFile);
Document inCommonMDDoc = ppMgr.parse(in);
Element metadataRoot = inCommonMDDoc.getDocumentElement();

// Get apropriate unmarshaller
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);

// Unmarshall using the document root element, an EntitiesDescriptor in this case
EntitiesDescriptor inCommonMD = (EntitiesDescriptor) unmarshaller.unmarshall(metadataRoot);

Additional Unmarshalling Information