Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This can be achieved using <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributeoverrides.aspx" rel="nofollow noreferrer">XmlAttributeOverrides</a>.</p> <p>Following is a basic example, <code>GetOverrides()</code> being the important part:</p> <pre><code>public class RailsXmlSerializer { private Type type; public RailsXmlSerializer(Type type) { this.type = type; } public void Serialize(Stream stream, object o) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer xmlSerializer = new XmlSerializer(type, GetOverrides(type)); xmlSerializer.Serialize(stream, o, ns); } public object Deserialize(Stream stream) { XmlSerializer xmlSerializer = new XmlSerializer(type, GetOverrides(type)); return xmlSerializer.Deserialize(stream); } private XmlAttributeOverrides GetOverrides(Type type) { XmlAttributeOverrides overrides = new XmlAttributeOverrides(); XmlAttributes classAttributes = new XmlAttributes(); classAttributes.XmlType = new XmlTypeAttribute(type.Name.ToLower()); overrides.Add(type, classAttributes); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(type)) { XmlAttributes propertyAttributes = new XmlAttributes(); propertyAttributes.XmlElements.Add(new XmlElementAttribute(property.Name.ToLower().Replace('_', '-'))); overrides.Add(type, property.Name, propertyAttributes); } return overrides; } } </code></pre> <p>Obviously, this needs to be a more robust implementation, possibly as a decorator for <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" rel="nofollow noreferrer">XmlSerializer</a>, with error and type checking. Of course, <code>GetOverrides()</code> can also be customized to provide the specific output you desire. That being said, here's the resulting output given a sample <code>Person</code> object:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;person&gt; &lt;first-name&gt;Jason&lt;/first-name&gt; &lt;last-name&gt;Bourne&lt;/last-name&gt; &lt;active&gt;true&lt;/active&gt; &lt;/person&gt; </code></pre> <p>And, given this input, deserialization is also performed correctly to provide the proper Person object.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload