Linq to xml, retreaving generic interface-based list

Posted by Rita on Stack Overflow See other posts from Stack Overflow or by Rita
Published on 2010-06-01T17:56:43Z Indexed on 2010/06/01 18:03 UTC
Read the original article Hit count: 215

Filed under:
|
|

I have an xml document that looks like this

    <Elements>
     <Element>
      <DisplayName />
      <Type />
     </Element>
    </Elements>

I have an interface,

interface IElement
{
string DisplayName {get;}
}

and a couple of derived classes:

public class AElement: IElement

public class BElement: IElement

What I want to do, is to write the most efficient query to iterate through the xml and create a list of IElement, containing AElement or BElement, based on the 'Type' property in the xml.

So far I have this:

IEnumerable<AElement> elements = 
from xmlElement in XElement.Load(path).Elements("Element")
where xmlElement.Element("type").Value == "AElement"
select new AElement(xmlElement.Element("DisplayName").Value);

return elements.Cast<IElement>().ToList();

But this is only for AElement, is there a way to add BElement in the same query, and also make it generic IEnumerable? Or would I have to run this query once for each derived type?

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml