Question

I want to write out a series of XML Elements. The values are mostly enums or bools. I would like to represent these enums and bools using the numerical values rather than the string names. (Mainly because I've already written the reading part which does this)

I don't know how to do this.

Object Class

 public class ApplicationConfiguration
        {
            public OperationalMode OperationalMode { get; set; }
            public bool MuteMedia { get; set; }
            public Stretch MediaStretch { get; set; }
            public DisplayMode DisplayMode { get; set; }
            public bool BlankSecondMonitor { get; set; }
            public String RemoteUri { get; set; }
        }

XML Writer Part

writer.WriteElementString("OperationalMode", configuration.OperationalMode.ToString());
writer.WriteElementString("MuteMedia",configuration.MuteMedia.ToString());
writer.WriteElementString("MediaStretch",configuration.MediaStretch.ToString());
writer.WriteElementString("DisplayMode",configuration.DisplayMode.ToString());
writer.WriteElementString("BlankSecondMonitor",configuration.BlankSecondMonitor.ToString();
writer.WriteElementString("RemoteUri",configuration.RemoteUri);

The above is writing out the enum string names and 'true' or 'false'.

I would like to use the numerical values, I can't figure out how.

Thanks

Was it helpful?

Solution

For the enum values, simply cast to integer before converting to a string:

writer.WriteElementString("MediaStretch",
                          ((int)configuration.MediaStretch).ToString());

For the booleans this is not possible, so if you want 0/1 values you can use the conditional operator:

writer.WriteElementString("MuteMedia",configuration.MuteMedia ? "1" : "0");

OTHER TIPS

Cast to enum value to int and than convert to string:

    ((int)configuration.MediaStretch).ToString(CultureInfo.InvariantCulture)

instead of configuration.MediaStretch.ToString()

Note that number formatting is culture specific - pass culture (normally InvariantCulture) for all cases where you read/write text data from files (like XML).

You can also use Convert.ToInt32 to achieve what you want for both enum and bool.

writer.WriteElementString("OperationalMode", Convert.ToInt32(configuration.OperationalMode).ToString());   
writer.WriteElementString("MuteMedia", Convert.ToInt32(configuration.MuteMedia).ToString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top