Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Using Extension Methods To Avoid XML Problems

2.33/5 (3 votes)
25 Jan 2011CPOL 9.5K  
You can avoid all of this by using the explicit cast operators:public XElement Element{ set { this.MyVar1 = (string)value.Element(MyVar1) ?? NO VALUE; this.MyVar2 = (string)value.Element(MyVar2) ?? NOVAL; }}Both XElement and XAttribute define...
You can avoid all of this by using the explicit cast operators:

C#
public XElement Element
{
    set
    {
        this.MyVar1 = (string)value.Element("MyVar1") ?? "NO VALUE";
        this.MyVar2 = (string)value.Element("MyVar2") ?? "NOVAL";
    }
}


Both XElement and XAttribute define explicit cast operators for:

string,<br />
bool, bool?, <br />
int, int?, <br />
long, long?, <br />
uint, uint?, <br />
ulong, ulong?, <br />
float, float?, <br />
double, double?, <br />
decimal, decimal?, <br />
DateTime, DateTime?, <br />
DateTimeOffset, DateTimeOffset?, <br />
TimeSpan, TimeSpan?, <br />
Guid, Guid?


For string and nullable value types, the operators simply return null if the element or attribute is null; for non-nullable value types, they throw an ArgumentNullException for null elements or attributes.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)