我希望通过一个Web服务返回以下类,该服务包含一个枚举类型作为其成员之一.
[Serializable,XmlRoot("GeoCoordinate")] public class GeoCoordinate { public enum AccuracyLevel { Unknown = 0,Country = 1,Region = 2,SubRegion = 3,Town = 4,PostalCode = 5,Street = 6,Intersection = 7,Address = 8,Premise = 9 } private AccuracyLevel _accuracy; // ... more members public AccuracyLevel Accuracy { get { return _accuracy; } set { _accuracy = value;} } }
这样可以正常工作,但会以下列形式返回结果:
<!-- ... --> <Accuracy>Unknown or Country or Region or SubRegion or Town or PostalCode or Street or Intersection or Address or Premise</Accuracy> <!-- ... -->
而不是表示枚举的字符串,我希望它只返回一个整数.这可以在不改变GeoCoordinate.Accuracy类型的情况下完成吗?
虽然这是一个黑客攻击,但我认为在每个枚举成员上使用
原文链接:https://www.f2er.com/xml/292035.htmlXmlEnumAttribute
是最适合这种情况的.如果这个枚举量要大得多,那么在Accuracy属性上使用XmlIgnore可能会更好,并且如该问题的另一个答案中所述,向该类添加一个额外的int属性.
Usng XmlEnumAttribute意味着只需要修改枚举本身,并且无论在何处使用,xml都会像int一样序列化.
public enum AccuracyLevel { [XmlEnum("0")] Unknown = 0,[XmlEnum("1")] Country = 1,[XmlEnum("2")] Region = 2,[XmlEnum("3")] SubRegion = 3,[XmlEnum("4")] Town = 4,[XmlEnum("5")] PostalCode = 5,[XmlEnum("6")] Street = 6,[XmlEnum("7")] Intersection = 7,[XmlEnum("8")] Address = 8,[XmlEnum("9")] Premise = 9 }