简体   繁体   中英

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

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

...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM