将XML值反序列化为枚举时处理额外的空格 [英] Handling extra spaces when deserializing XML values to enums
问题描述
我一直在想,是否可以这样做。
如果XML响应的值不正确,那么这将是一个很大的帮助映射到枚举。
我正在处理的情况是当一个预期值有一个尾随空格,枚举是期望没有。
XML:
&Foo>
< Bar> EnumValue< / Bar>
< / Foo>
枚举:
code> public enum MyEnum
{
[XmlEnum(EnumValue)]
EnumValue
}
类:
public class Foo
{
[XmlElement(Bar)]
public MyEnum myEnum {get;组;我已经调查过使用自定义属性(而不是XmlEnum),但是,要修剪值,但在反序列化过程中似乎没有达到。
有没有办法在反序列化之前/之间修剪XML值(在需要时),以便该值可以正确映射到枚举?
-
我应该补充说,我可以't 对XML的发送方式进行了任何更改,我只能处理响应。
此外,只需将属性参数更改为[XmlEnum EnumValue)]修复了这个问题,但这并不令人满意,因为XML值可能会在以后更改。
解决方案请尝试这样:
public class Foo
{
[XmlIgnore]
public MyEnum myEnum {get;组;
[XmlElement(Bar)]
[EditorBrowsable(EditorBrowsableState.Never)]
public string _myEnum
{
get {return myEnum。的ToString(); }
set {myEnum =(MyEnum)Enum.Parse(typeof(MyEnum),value.Trim()); }
}
}
I've been wondering if it's possible to do this.
It would be a great help in cases where an XML response has incorrect values that are needing to be mapped to enums.
The case I'm dealing with specifically is when an expected value has a trailing space and the enum is expecting it without.
XML:
<Foo>
<Bar>EnumValue </Bar>
</Foo>
Enum:
public enum MyEnum
{
[XmlEnum("EnumValue")]
EnumValue
}
Class:
public class Foo
{
[XmlElement("Bar")]
public MyEnum myEnum { get; set; }
}
I've investigated using a custom attribute (instead of "XmlEnum") to trim the values but it doesn't seem to be reached during the deserialization.
Is there a way to trim XML values (when needed) before/during deserialization so that the value can be mapped to the enum correctly?
-
I should add that I can't make any changes to how the XML is sent, I can only deal with the response.
Also, simply changing the attribute parameter to [XmlEnum("EnumValue ")] fixes the issue, but this is not satisfactory as the XML value could be altered at a later date.
解决方案 Please try this:
public class Foo
{
[XmlIgnore]
public MyEnum myEnum { get; set; }
[XmlElement("Bar")]
[EditorBrowsable(EditorBrowsableState.Never)]
public string _myEnum
{
get { return myEnum.ToString(); }
set { myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), value.Trim()); }
}
}
这篇关于将XML值反序列化为枚举时处理额外的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!