views:

32

answers:

2

I've got a few classes and structures that I use XML serialization to save and recall data, but a feature that I'd like to have is to output integers in hex representation. Is there any attribute that I can hang on these structure to make that happen?

A: 

You can implement fully custom serialization, but that's probably a bit much for this. How about exposing a property MyIntegerAsHex, that returns the integer as a string, formatted as a hexadecimal number: MyInteger.ToString("X"); The property will need a setter, even though it's a calculated field, so that the string from the serialized object can be fed into a new instance on deserialization.

You can then implement a deserialization callback, or just put code in the setter, that will parse the hex number to a decimal integer when the object is deserialized: MyInteger = int.Parse(IntegerAsHex, NumberStyles.AllowHexNumber);

So, in summary, your property would look something like this:

public string MyIntegerAsHex
{
   get { return MyInteger.ToString("X"); }
   set { MyInteger = int.Parse(value, NumberStyles.AllowHexNumber); }
}

Then, if you didn't want to see the number as a decimal integer in the XML file, just tag it with [XmlIgnore].

KeithS
A: 

There's a bit of code smell, but the following will work:

public class ViewAsHex
{
    [XmlIgnore]
    public int Value { get; set; }

    [XmlElement(ElementName="Value")]
    public string HexValue
    {
        get
        {
            // convert int to hex representation
            return Value.ToString("x");
        }
        set
        {
            // convert hex representation back to int
            Value = int.Parse(value, 
                System.Globalization.NumberStyles.HexNumber);
        }
    }
}

Test the class in a console program:

public class Program
{
    static void Main(string[] args)
    {
        var o = new ViewAsHex();
        o.Value = 258986522;

        var xs = new XmlSerializer(typeof(ViewAsHex));

        var output = Console.OpenStandardOutput();
        xs.Serialize(output, o);

        Console.WriteLine();
        Console.WriteLine("Press enter to exit.");
        Console.ReadLine();
    }
}

The result:

<?xml version="1.0"?>
<ViewAsHex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <Value>f6fd21a</Value>
</ViewAsHex>
code4life