3

I have thw following XML Code that I want to deserialize:

<a>
   <b> n/a </b>
</a>

Now b is normally an integer, but sometimes "n/a" for not available. Whenever I deserialize the above XML, I get an Exception that I use a wrong format... what is correct. But I need the int simply to be a null value

public class a
{
    Nullable<int> b;
}
Hint
  • 130
  • 9

2 Answers2

1

The only way you could do that would be to use something like:

[XmlIgnore]
public int? B {get;set;}

public bool ShouldSerializeBSerialized() {
    return B.HasValue;
}
[XmlElement("b")]
public string BSerialized {
    get { return B.ToString(); }
    set {
       int tmp;
       if(value != null && int.TryParse(value.Trim(), out tmp))
       {
           B = tmp;
       }
    }
}

Here:

  • B is the int? we'll use to store the data
  • BSerialized is a shim property that handles the parsing etc
  • ShouldSerializeBSerialized ensures we only serialize valid data
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

have a look at the below:

Serialize a nullable int

Community
  • 1
  • 1
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70