开发者

XmlSerializer enumeration deserialization failing on (non existent) whitespace

开发者 https://www.devze.com 2023-02-01 06:12 出处:网络
I have an object I\'m deserializing which contains an enum \'JourneyPatternLinkDirectionEnumeration\', it\'s used as a value for a node \'Direction\'.

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.开发者_如何学Python 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)


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.


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);}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号