XMLBeans and namespaces
When saving from XMLBeans and using XmlOptions to pretty print, I kept getting a strange problem with the namespaces. The root node was ok as I was using XmlOptions.xmlOptions.setUseDefaultNamespace() but lower down the tree, the namespace prefixes weren’t coming out correctly. Instead of “saml” I was getting “urn”:
<urn:NameIdentifier xmlns:urn=”urn:oasis:names:tc:SAML:1.0:assertion”>testID</saml:NameIdentifier>
With some help from the XMLBeans list, I’d overlooked XmlOptions.setSaveSuggestedPrefixes(Map). So bunging in the prefixes I wanted to save:
HashMap ns = new HashMap();
ns.put(“urn:oasis:names:tc:SAML:1.0:protocol”, “samlp”);
ns.put(“urn:oasis:names:tc:SAML:1.0:assertion”, “saml”);
ns.put(“http://www.w3.org/2000/09/xmldsig#”, “ds”);
xmlOptions.setSaveSuggestedPrefixes(ns);
sorted the problem:
<saml:NameIdentifier>testID</saml:NameIdentifier>
Summary of XmlOptions namespace handling
With no namespace processing in XmlOptions, the output of save() is:
<?xml version=”1.0″ encoding=”UTF-8″?>
<urn:Request xmlns:urn=”urn:oasis:names:tc:SAML:1.0:protocol”>
<urn:AttributeQuery>
<urn1:Subject xmlns:urn1=”urn:oasis:names:tc:SAML:1.0:assertion”>
<urn1:NameIdentifier>testID</urn1:NameIdentifier>
</urn1:Subject>
</urn:AttributeQuery>
</urn:Request>
Using XmlOptions.setUseDefaultNamespace() you get:
<?xml version=”1.0″ encoding=”UTF-8″?>
<Request xmlns=”urn:oasis:names:tc:SAML:1.0:protocol”>
<AttributeQuery>
<urn:Subject xmlns:urn=”urn:oasis:names:tc:SAML:1.0:assertion”>
<urn:NameIdentifier>testID</urn:NameIdentifier>
</urn:Subject>
</AttributeQuery>
</Request>
Telling XmlOptions which namespace prefixes to use gives you explicit prefixing:
HashMap ns = new HashMap();
ns.put(“urn:oasis:names:tc:SAML:1.0:protocol”, “samlp”);
ns.put(“urn:oasis:names:tc:SAML:1.0:assertion”, “saml”);
ns.put(“http://www.w3.org/2000/09/xmldsig#”, “ds”);
xmlOptions.setSaveSuggestedPrefixes(ns);
<?xml version=”1.0″ encoding=”UTF-8″?>
<samlp:Request xmlns:samlp=”urn:oasis:names:tc:SAML:1.0:protocol”>
<samlp:AttributeQuery>
<saml:Subject xmlns:saml=”urn:oasis:names:tc:SAML:1.0:assertion”>
<saml:NameIdentifier>testID</saml:NameIdentifier>
</saml:Subject>
</samlp:AttributeQuery>
</samlp:Request>
Now, combine XmlOptions.setSaveSuggestedPrefixes() with XmlOptions.setSaveAggresiveNamespaces() and you get a tidy output:
<?xml version=”1.0″ encoding=”UTF-8″?>
<samlp:Request xmlns:samlp=”urn:oasis:names:tc:SAML:1.0:protocol” xmlns:saml=”urn:oasis:names:tc:SAML:1.0:assertion”>
<samlp:AttributeQuery>
<saml:Subject>
<saml:NameIdentifier>testID</saml:NameIdentifier>
</saml:Subject>
</samlp:AttributeQuery>
</samlp:Request>
Comment from Amit
Time: 21/6/2010, 2:46 pm
thanks for your help. That made me fix my issue quickly.