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?
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With