« The great questions answered | Main | Dr Who advent calendar »

September 20, 2006

Using XmlElement in XML serialisation

Suppose you have a message definition where one of the elements can contain arbitrary XML.  The classic example is header-plus-payload; another scenario is magic cookie (an opaque blob that the receiver can return to the sender at a later date).

Now XSD has two ways of saying "anything goes here": declaring an element of type xs:anyType, and declaring an xs:any element.

The first of these surfaces in .NET as a property of type Object.  This is pretty useless, because as soon as you try to put anything into it, you get an InvalidOperationException telling you the type was unexpected and you need to supply an XmlIncludeAttribute.

The second of these surfaces as a property of type XmlElement, called Any and with the XmlAnyElementAttribute.  This is technically usable, but not very nice because there's no way to give the property a meaningful name, and because it doesn't help if the blob lives in a specific element of the schema.

So how do we get a property of type XmlElement but still have a named element of the schema and get a nice named property at the CLR level?

The answer is to use a variant of the xs:any trick, but instead of having an xs:any trying to stand in for the blob itself, you define an element which contains a sequence which contains a single xs:any.  Thus:

<xs:element name="MyMessage">
  <xs:complextype>
    <xs:sequence>
      <xs:element name="Header" type="MyHeader">
      <xs:element name="Body">
        <xs:complextype>
          <xs:sequence>
            <xs:any>
          </xs:sequence>
        </xs:complextype>
      </xs:element>
    </xs:sequence>
  </xs:complextype>
</xs:element>

This generates the following C#-level interface:

public partial class MyMessage
{
  public MyHeader Header { get; set; }
  public XmlElement Body { get; set; }
}

which is what I want.

September 20, 2006 in Software | Permalink

TrackBack

TrackBack URL for this entry:
https://www.typepad.com/services/trackback/6a00d8341c5c9b53ef00d835698c3a69e2

Listed below are links to weblogs that reference Using XmlElement in XML serialisation:

Comments