The default behavior of XML serialization (to_xml) for ActiveRecord objects will emit ‘type’ and ‘nil’ attributes that are similar to XML Schema Instance attributes, but aren’t set in a XML Namespace.
For example, a model might produce an output like this:
<user>
<username nil="true" />
<first-name type="string">Name</first-name>
</user>
Is there anyway to get to_xml to utilize the XML Schema Instance namespace and prefix the attributes and the values?
Using the above example, I’d like to produce the following:
<user xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xs="http://www.w3.org/1999/XMLSchema">
<username xsi:nil="true" />
<first-name xsi:type="xs:string">Name</first-name>
</user>
I ran into something similar, but when calling #to_xml on a Hash, not on an AR instance.
I came up with this helper:
It’s then used like so:
Note that I opted to keep the existing nil= and type= attributes, and add my own xsi-prefixed nil, however it’s trivial to replace them instead.