Search code examples
c#xmlenumsxmlreaderxmlwriter

Read/Write Enum to/from XML


I'm writing an enum value with an XmlWriter, and it look something like this in the xml:

<Tile>Plain</Tile>

writer.WriteValue(tile.ID.ToString()); // ID's type is the enum

Plain being one of the enum values. Now when I try to read this, though it won't work.

(TileID)reader.ReadElementContentAs(typeof(TileID), null);

I do this when my reader.Name == "Tile", which should work, though it apparently can't convert the string to my enum. Is there any way to either fix the writing, so I don't have to do the .ToString() (since if I don't I get an error: "TileID cannot be cast to string".) or fix the reading?

Thanks.


Solution

  • I would suggest using Enum.TryParse

    var enumStr = reader.ReadString();
    TitleID id;
    if (!Enum.TryParse<TitleID>(enumStr, out id)
    {
        // whatever you need to do when the XML isn't in the expected format
        //  such as throwing an exception or setting the ID to a default value
    }