C#C
C#4y ago
Iceman228

XML Deserialization Null Exception

I have an XML element which usually looks like this
<LoginName><![CDATA[Name]]></LoginName>

It is possible thought that someone deleted the whole cdata part and if that happened, when trying to deserialize it, I get a NullReferenceException.
public static XmlCDataSection ToCData(this string str)
{
    return new XmlDocument().CreateCDataSection(str);
}

[XmlIgnore] public string LoginName { get; set; }
[XmlElement("LoginName")]
public XmlCDataSection CDataLoginName
{
    get => LoginName.ToCData();
    set => LoginName = value.Value;
}

How can I prevent this exception?
Was this page helpful?