[Mono-list] Xml.Serialization empty element

Jonathan Gilbert 2a5gjx302 at sneakemail.com
Tue Apr 18 13:05:32 EDT 2006


At 09:51 AM 18/04/2006 +0200, Lluis wrote:
>El vie, 14-04-2006 a las 20:17 +0200, Dominik Zablotny escribió:
>> Hello
>> 
>> I would like to represent empty XML element as a bool that is true where
>> element is present, and false  when it's not. Serialized element must be
>> empty, so DefaultValue("false") is not sufficient. For now the best way
>> I figured out is using extra class for that element and extra bool
>> property, but since this situation is quite common in my program I
>> wonder if there is a better way to do it?
>> 
>
>There isn't a better way. XmlSerializer does not have support for what
>you want to do.

Just to elaborate on this (for the original poster), XML serializtion was
designed with the goal of generating XML for instances of existing data
types, and so using it for the inverse mapping -- taking an arbitrary XML
structure and mapping a hierarchy of C# data types onto it -- is something
that is not guaranteed to work. It sounds like you've done well, in that
you are successfully deserializing your XML to C# classes. When looking for
features like what you want here, though, you need to consider whether the
XML structure you want to parse could possibly be generated by XML
serialization directly from C# objects. Could a 'bool' ever get serialized
to <arbitraryelement />? :-)

One approach to slightly sweeten the syntax might be to add an implicit
conversion from your dummy class to 'bool':

using System;

class Test
{
  static void Main()
  {
    Bonk q = new Bonk();

    if (q)
      Console.WriteLine("true");
    else
      Console.WriteLine("false");

    q = null;

    if (q)
      Console.WriteLine("true");
    else
      Console.WriteLine("false");
  }
}

class Bonk
{
  public static implicit operator bool (Bonk o)
  {
    return (o != null);
  }
}

Output:

true
false

Jonathan Gilbert


More information about the Mono-list mailing list