2

I have an object I'm deserializing which contains an enum 'JourneyPatternLinkDirectionEnumeration', it's used as a value for a node 'Direction'.

When 'Direction' is specified with a value, or not specified and it's represented in xml as

<Direction />

Everything works fine. However, if it's in the xml as

<Direction></Direction>

I get the following error:

"Instance validation error: '' is not a valid value for JourneyPatternLinkDirectionEnumeration."

My code is as follows:

var xmlTextReader = new XmlTextReader(xmlDocUri);
xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;
xmlTextReader.Normalization = false;

var serializer = new XmlSerializer(typeof(T),  typeof(T).Assembly.GetTypes());

ouput = (T)serializer.Deserialize(xmlTextReader);

Any thoughts? Is there a better way to do this.

(Sorry I can't post the full code, the xml doc is a 65000-line TransXchange doc)

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Doobi
  • 4,844
  • 1
  • 22
  • 17

2 Answers2

3

I don't think you have a choice here, if it's an error, then it's an error. Change the source XML, or declare your value as a string, and provide a non-serialized enum wrapper property, or create a wrapper class for the enum type which implements IXmlSerializable.

fejesjoco
  • 11,763
  • 3
  • 35
  • 65
2

There are a few places where an empty (self-closing) element gets treated as significantly different to an element that has an empty text content.

Assuming you don't control the source, I wonder if in this case you should be pragmatic and change it to a string member:

public string Direction {
    get { return enumField.ToString(); }
    set { enumField = (EnumType)Enum.Parse(typeof(EnumType), value);}
}
dbc
  • 104,963
  • 20
  • 228
  • 340
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900