【问题标题】:How to query xsi:type from an attribute using Linq to XML?如何使用 Linq to XML 从属性中查询 xsi:type?
【发布时间】:2010-01-27 21:27:52
【问题描述】:

鉴于此 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 属性吗?

谢谢,

瑞克

【问题讨论】:

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


    【解决方案1】:

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

    ...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多