XAttribute Extension Methods

<!-- example xml-->
<elements>
  <element element="First">First</element>
  <elemen element="10">10</element>
  <element element="2010-02-02">2010-02-02</element>
</elements>
XElement xml = XElement.Parse("<elements>...</elements>");


T OfType<T>()
Converts the value of the XAttribute to typeof(T)
string StringValue = (from x in xml.Descendants("element").Attributes() 
                      where x.Value == "First" 
                      select x)
                      .FirstOrDefault()
                      .OfType<string>();

int IntegerValue = (from x in xml.Descendants("element").Attributes() 
                    where x.Value == "10" 
                    select x)
                    .FirstOrDefault()
                    .OfType<int>();

DateTime DateTimeValue = (from x in xml.Descendants("element").Attributes() 
                          where x.Value == "2010-02-02" 
                          select x)
                          .FirstOrDefault()
                          .OfType<DateTime>();

Last edited Feb 20, 2010 at 9:38 AM by jole, version 1

Comments

No comments yet.