Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query xsi:type from an attribute using Linq to XML?

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

like image 240
RickB Avatar asked Jan 27 '10 21:01

RickB


1 Answers

XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

...

var type = e.Attributes(ns + "type");

like image 126
devuxer Avatar answered Nov 02 '22 19:11

devuxer