Florian Baierl
Florian Baierl

Reputation: 2481

XML Serialization Type Converter

In Json I can do this:

 [JsonProperty("type")]
 [JsonConverter(typeof(MyTpeConverter))]
 public BoxType myType { get; set; }


 .....
 public class BoxTypeEnumConverter : JsonConverter
 {
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
     ....
    }
 }

Is this also possible when working with XML?

[XmlElement("isFolder")]
[XmlConvert()] // ???
public string IsFolder { get; set; }

My Xml File has e.g.

....
<isFolder>t</isFolder>
....

I want that "t" to be "true".

Upvotes: 3

Views: 3208

Answers (1)

Vladimir Gondarev
Vladimir Gondarev

Reputation: 1243

Threre are two ways: Simple way: :)

[XmlElement("isFolder")]
public string IsFolderStr { get; set; }
[XmlIgnore]
public bool IsFolder { get{ ... conversion logic from IsFolderStr is here... }}

second way is to create a class that would handle custom convertion:

public class BoolHolder : IXmlSerializable
{
    public bool Value { get; set }

    public System.Xml.Schema.XmlSchema GetSchema() {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader) {
        string str = reader.ReadString();
        reader.ReadEndElement();

        switch (str) {
            case "t":
                this.Value = true;
    ...
    }
}

and replace definition of the property with BoolHolder:

public BoolHolder IsFolder {get;set;}

Upvotes: 8

Related Questions