How to serialize byte array to XML using XmlSerializer in C#?

拥有回忆 提交于 2019-11-30 17:41:05

The XmlSerializer by default will encode the byte arrays using base 64 encoding. If you use this site and paste in IzE=, and decode it, the result will be #1. You can change the encoding by setting the XmlElementAttribute.DataType. I'm not sure if [XmlElement(DataType = "string")] will work, but you can try it. Using [XmlElement(DataType = "hexBinary")] will generate the raw bytes.

I got this to work using the following:

  public class MySerializableClass
  {   
    [XmlIgnore]
    public string NaughtyXmlCharactersAsString { get; set; }

    [XmlElement(ElementName = "NaughtyXmlCharacters", DataType = "hexBinary")]
    public byte[] NaughtyXmlCharactersAsBytes
    {
        get { return Encoding.UTF8.GetBytes(NaughtyCharactersAsString ?? string.Empty); }
        set { NaughtyXmlCharactersAsString = Encoding.UTF8.GetString(value); }
    }

I would then only access the "AsString" version of the property.

This is how I did it:

public class MySerializableClass
{
    private string dummy;

    [XmlElement("NaughtyXmlCharacters")]
    public string NaughtyXmlCharactersAsString
    {
       get 
       {
           return BitConverter.ToString(NaughtyXmlCharacters);
       }
       set
       {
           // without this, the property is not serialized.
           dummy = value;
       }
    }

    [XmlIgnore]
    public byte[] NaughtyXmlCharacters
    {
        get;
        set;
    }
}

The bytes are then formatted as hexadecimal values and separated with a minus sign: 00-AF-B1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!