Check for XElement globally

I have a class that takes care of reading and storing an XML file. Now a simple version looks like this:

public class EstEIDPersoConfig
{
    public bool LaunchDebugger { get ; set; }
    public string Password { get; set; }
    public int Slot { get; set; }
    public string Reader { get; set; }
    public string TestInput { get; set; }
    public bool Logging { get; set; }

    public EstEIDPersoConfig()
    {
        XElement xml = XElement.Load(myxml.xml);
        XElement Configuration = xml.Element("Configuration");

        LaunchDebugger = Convert.ToBoolean(Configuration.Element("LaunchDebugger").Value);
        Password = Configuration.Element("Password").Value;
        Slot = Convert.ToInt32(Configuration.Element("Slot").Value);
        Reader = Configuration.Element("Reader").Value;
        TestInput = Configuration.Element("TestInput").Value;
        Logging = Convert.ToBoolean(Configuration.Element("Logging").Value);
     }
 }

And it will be later. so the problem is that if some element does not exist in xml, I get System.NullReferenceException. So I need to check if the item is nullor not. Here is one way to do this:

var value = Configuration.Element("LaunchDebugger").Value;
if (value != null)
    LaunchDebugger = Convert.ToBoolean(value);
else
    throw new Exception("LaunchDebugger element missing from xml!");

But doing this for each element would be too much. Therefore, I need good ideas on how to simplify this system so that it does not fall into 1000 lines of code.

EDIT: Last edited code snippet, the idea was not to set a default value, the idea was to notify the user that this element was not in XML.

+5
6

abatischev, .

Microsoft , XElement .

LaunchDebugger = (bool?)Configuration.Element("LaunchDebugger");

null, ,

LaunchDebugger = (bool)(Configuration.Element("LaunchDebugger") ?? true);

, ,

LaunchDebugger = (bool)(Configuration.Element("LaunchDebugger") ?? false);

-. , , , , .

+4
(bool)Configuration.Element("LaunchDebugger")

(bool?)Configuration.Element("LaunchDebugger")

.

. MSDN:

+4

Int32, boolean .

public static void GetElementValue(XElement xElement, string parameter, out bool value)
    {
        var stringValue = xElement.Element(parameter).Value;
        value = false;
        if (value != null)
            value = Convert.ToBoolean(stringValue);
    }
+2

, :

    public static T GetValue<T>(
            this XElement @this,
            XName name, 
            Func<XElement, T> cast, 
            Func<T> @default)
    {
        var e = @this.Element(name);
        return (e != null) ? cast(e) : @default();
    }

, factory.

:

LaunchDebugger = Configuration.GetValue("LaunchDebugger",
    x => Convert.ToBoolean(x), () => false);
Password = Configuration.GetValue("CMKPassword", x => (string)x, () => "");
Slot = Configuration.GetValue("CMKSlot", x => (int)x, () => -1);
Reader = Configuration.GetValue("Reader", x => (string)x, () => "");
TestInput = Configuration.GetValue("TestInput", x => (string)x, () => "");
Logging = Configuration.GetValue("Logging",
    x => Convert.ToBoolean(x), () => false);
+2

:

public static class XElementExtensions
{
    public static bool AsBoolean(this XElement self, bool defaultValue)
    {
        if (self == null)
        {
            return defaultValue;
        }
        if (!string.IsNullOrEmpty(self.Value))
        {           
            try
            {
                return XmlConvert.ToBoolean(self.Value);
            }
            catch
            {
                return defaultValue;
            }
        }
        return defaultValue;
    }
}

SnippetCompiler:

XElement test = new XElement("test", 
    new XElement("child1"),
    new XElement("child2", new XText("true")),
    new XElement("child3", new XText("false")),
    new XElement("child4", new XText("rubbish")));

WL(test.Element("child1").AsBoolean(false)); // note, "child1" has no value (or is `""`)
WL(test.Element("child2").AsBoolean(false));
WL(test.Element("child3").AsBoolean(false));
WL(test.Element("child4").AsBoolean(false));
WL(test.Element("child5").AsBoolean(false)); // note, "child5" doesn't exist        

:

False
True
False
False
False

, AsBoolean(defaultValue), , true!

, ?? null. , :

LaunchDebugger = XmlConvert.ToBoolean(Configuration.Element("LaunchDebugger").Value) ?? false;

NullReferenceException, XML .

+1

You can define a method to extract the value for you and do some checking on the null value. Thus, return the value to your own method as follows:

public string GetXMLValue(XElement config, string elementName){
    var element = Configuration.Element(elementName);

    if(element == null)
        return String.Empty;

    return element.Value;
}

Of course, you can extend this to work correctly with parsing in boolean, etc.

+1
source

All Articles