c# - How can I cast XNode to a custom type? -
my linq xml query
xdocument xdoc = xdocument.load("test.xml"); ienumerable<xnode> lv1s = lv1 in xdoc.descendants("resources") select lv1.firstnode;
which returns list of
<entry> <key>keyname</key> <value>valuename</value> </entry>
how can convert result of query list of 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 { { return this.keyfield; } set { this.keyfield = value; } } /// <remarks/> public string value { { return this.valuefield; } set { this.valuefield = value; } } }
the elements of type xnode
, representing elements of xml. cannot cast them, need use new
create objects of desired type:
var converted = lv1s.oftype<xelement>().select(lv1 => new entry { key = lv1.element("key").value , value = lv1.element("value").value });
filtering xnode
s down xelement
using oftype<t>
lets skip nodes of xml tree not elements, e.g. comments.
Comments
Post a Comment