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!
You can parse the xml attribute value back to an enum type with:
But I don’t think you will get really far with your “special” values (
3,a/etc.).Why don’t you define your enum as
And write a static method to convert a string to an enum member?
One thing you could look into for implementing such a method would be to add custom attributes to the enum members containing their string representation – if a value doesn’t have an exact counterpart in the enumeration, look for a member with the attribute.
Creating such an attribute is easy:
And then you can use them in your enum:
These two methods will help you parse a string into an enum member of your choice:
And while I’m at it: here is the other way round 😉