Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output hex numbers via XML Serialization in c#?

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?

like image 784
Gio Avatar asked Oct 01 '10 15:10

Gio


People also ask

What is the correct way of using XML serialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.

Is XML a serialization format?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

What is the difference between binary serialization and XML serialization?

Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.

What is XmlSerializer C#?

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.


1 Answers

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">
  <Value>f6fd21a</Value>
</ViewAsHex>
like image 134
code4life Avatar answered Nov 15 '22 05:11

code4life