How to query xsi:type from an attribute using Linq to XML?
c#, linq, linq-to-xml, xml
Solution
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
...
var type = e.Attributes(ns + "type");
Problem
Given this xml: ``` <?xml version="1.0" encoding="utf-8"?> <EntityDefinition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <components> <component xsi:type="TypeA"> <Property1>100</Property1> </component> <component xsi:type="TypeB"> <Property2>100</Property2> </component> </components> </EntityDefinition> ``` I would like to loop on the components and instantiate each object based on the xsi:type attribute. Here’s some Linq to XML code: ``` IEnumerable<XElement> components = from c in elementsFromFile.Descendants("component") select (XElement)c; foreach (XElement e in components) { var type = e.Attributes("xsi:type"); } ``` Unfortunately, the line “var type = e.Attributes("xsi:type");” does not work because colons are not allowed in a name. Any idea on how I can query the xsi:type attribute from each element? Thank you, Rick