XElement Extension Methods

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


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

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

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

XmlNode ToXmlNode()
Converts the XElement to an instance of System.Xml.XmlNode.

XmlDocument ToXmlDocument()
Converts the XElement to an instance of System.Xml.XmlDocument.

XElement RemoveNamespace(string namespaceAttribute)
Removes the namespace attribute/s in the xml content.
// doc is an instance of a XDocument that has a namespace attribute
var without = from attr in doc.Root.Descendants().Attributes()
              where attr.IsNamespaceDeclaration
              select attr.Parent.RemoveNamespace(attr.Name.LocalName);

Last edited Feb 15, 2010 at 9:21 AM by jole, version 5

Comments

No comments yet.