如何使用Linq从XML查询xsi:type?

时间:2010-01-27 21:27:53

标签: c# xml linq linq-to-xml

鉴于此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>

我想循环组件并基于xsi:type属性实例化每个对象。

以下是一些Linq to XML代码:

    IEnumerable<XElement> components =
    from c in elementsFromFile.Descendants("component")
    select (XElement)c;

    foreach (XElement e in components)
    {
        var type = e.Attributes("xsi:type");
    }

不幸的是,“var type = e.Attributes(”xsi:type“);”行不起作用,因为名称中不允许使用冒号。

如何查询每个元素的xsi:type属性?

谢谢,

瑞克

1 个答案:

答案 0 :(得分:9)

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

...

var type = e.Attributes(ns +“type”);

相关问题