Ric*_*ckB 8 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>
Run Code Online (Sandbox Code Playgroud)
我想循环组件并基于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");
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,"var type = e.Attributes("xsi:type");"行不起作用,因为名称中不允许使用冒号.
关于如何从每个元素查询xsi:type属性的任何想法?
谢谢,
干草堆
XNamespace ns =" http://www.w3.org/2001/XMLSchema-instance ";
...
var type = e.Attributes(ns +"type");