2

Normally in C# Xml types are marked with attributes to define the way how they get serialized:

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace=
"urn:xmlns:25hoursaday-com:my-bookshelf")]
public class bookType {

    /// <remarks/>
    public string title;

    /// <remarks/>
    public string author;

   /// <remarks/>
   [System.Xml.Serialization.XmlElementAttribute("publication-date", 
DataType="date")]      
    public System.DateTime publicationdate;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string publisher;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute("on-loan")]
    public string onloan;
}

Now when it comes to the point that I like to use POCOS without these attributes that I could potentially reuse to do an OR-Mapping with e.g. NHibernate, then it would be nice to define the serialization way in a manner without altering the types to be serialized.

The question is: Is there a way to declerativeley define the way a type gets serialized by e.g.: a mapping xml file.

schoetbi
  • 12,009
  • 10
  • 54
  • 72

1 Answers1

1

Yes:

    XmlAttributeOverrides attribs = new XmlAttributeOverrides();
    attribs.Add(typeof(bookType), new XmlAttributes
    {
        XmlType = new XmlTypeAttribute { Namespace = "urn:xmlns:25hoursaday-com:my-bookshelf" },
    });
    attribs.Add(typeof(bookType), "publicationdate", new XmlAttributes
    {
        XmlElements = { new XmlElementAttribute("publication-date") { DataType = "date" } }
    });
    attribs.Add(typeof(bookType), "publisher", new XmlAttributes
    {
        XmlAttribute = new XmlAttributeAttribute()
    });
    attribs.Add(typeof(bookType), "onloan", new XmlAttributes
    {
        XmlAttribute = new XmlAttributeAttribute("on-loan")
    });

Then serialize with:

    XmlSerializer s = new XmlSerializer(typeof(bookType), attribs);
    var obj = new bookType { title = "a", author = "b",
        publicationdate = DateTime.Now, publisher = "c", onloan = "d"};
    s.Serialize(Console.Out, obj);

HOWEVER

and I can't caution this strongly enough; you must cache and re-use the XmlSerializer objects created in this way, as each one creates a dynamic serialization assembly that cannot be unloaded. If you don't cache and re-use, you will swamp the memory.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900