:
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 .