OrElse OrElse - 21 days ago 6
C# Question

How can I cast XNode to a custom type?

My linq to xml query is

XDocument xdoc = XDocument.Load("test.xml");
IEnumerable<XNode> lv1s = from lv1 in xdoc.Descendants("resources") select lv1.FirstNode;


which returns a list of

<entry>
<key>keyName</key>
<value>valueName</value>
</entry>


How can i convert the result of the query to a list of the following class?

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class entry
{

private string keyField;

private string valueField;

/// <remarks/>
public string key
{
get
{
return this.keyField;
}
set
{
this.keyField = value;
}
}

/// <remarks/>
public string value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}

Answer

The elements you get are of type XNode, representing elements of XML. You cannot cast them, so you need to use new to create objects of your desired type:

var converted = lv1s.OfType<XElement>().Select(lv1 => new entry {
    key = lv1.Element("key").Value
,   value = lv1.Element("value").Value
});

Filtering XNodes down to XElement using OfType<T> lets you skip nodes of your XML tree that are not elements, e.g. comments.

Comments