Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping xml values to enum type

Tags:

c#

enums

xml

I need to parse a XML file which I get from third party to C# objects. Some of the XML I receive have enumeration values which I want to store in an enum type.

For example, I've got the following xsd of the xml file:

<xsd:simpleType name="brandstof">
  <xsd:restriction base="xsd:string">
    <!--  Benzine --> 
    <xsd:enumeration value="B" /> 
    <!--  Diesel --> 
    <xsd:enumeration value="D" /> 
    <!--  LPG/Gas --> 
    <xsd:enumeration value="L" /> 
    <!--  LPG G3 --> 
    <xsd:enumeration value="3" /> 
    <!--  Elektrisch --> 
    <xsd:enumeration value="E" /> 
    <!--  Hybride --> 
    <xsd:enumeration value="H" /> 
    <!--  Cryogeen --> 
    <xsd:enumeration value="C" /> 
    <!--  Overig --> 
    <xsd:enumeration value="O" /> 
  </xsd:restriction>
</xsd:simpleType>  

I want to map this to an enum and I got this far:

public enum Fuel
{
    B,
    D,
    L,
    E,
    H,
    C,
    O
}

The problem I have is that the xml can contain a value of 3 which I can't seem to put in the enum type. Is there any solution to put this value in the enum.

I also can get other values with a - or a / in them and which I want to put in an enum type.
Anu suggestions are welcome!

like image 475
Gerard Avatar asked Jun 09 '11 13:06

Gerard


People also ask

Can we assign value to enum?

Enum ValuesYou can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.

What is enum in XML?

This annotation, together with XmlEnum provides a mapping of enum type to XML representation. An enum type is mapped to a schema simple type with enumeration facets. The schema type is derived from the Java type specified in @XmlEnum.value().

Can we assign string to enum?

We can use Enum. GetName static method to convert an enum value to a string. The following code uses Enum. GetName static method that takes two arguments, the enum type and the enum value.

Can enum be used as variable type?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.


1 Answers

Decorate with the XmlEnum attribute: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlenumattribute.aspx

public enum Fuel
{
    [XmlEnum("B")]
    Benzine,
    [XmlEnum("D")]
    Diesel,
    [XmlEnum("L")]
    LpgGas,
    [XmlEnum("3")]
    LpgG3,
    [XmlEnum("E")]
    Elektrisch,
    [XmlEnum("H")]
    Hybride,
    [XmlEnum("C")]
    Cryogeen,
    [XmlEnum("O")]
    Overig
}
like image 165
Andrew Avatar answered Sep 29 '22 14:09

Andrew