【发布时间】:2016-08-24 13:51:10
【问题描述】:
我的 XML 包含这样的元素
<Value xsi:type="xsd:short">0</Value>
<Value xsi:type="xsd:string">foo</Value>
<Value xsi:type="xsd:boolean">false</Value>
<!-- ... many other types -->
我如何自动解析/反序列化它,以便我使用 xsd: 类型(例如 System.Int16、System.String、@987654326 @)?
这是我尝试过的,但它有点脆弱,所有这些 .NET XML API 中必须有一种内置方式。
foreach (var value in XDocument.Load(new StreamReader(@"c:\bar.xml")).Descendants("Value"))
{
var actualValue = GetValue(value);
}
...
// TODO: Get rid of this hand written method, .NET should do this for me
private static object GetValue(XElement value)
{
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
var type = value.Attributes(ns + "type").Single().Value;
switch (type)
{
case "xsd:short":
return (short)value;
case "xsd:boolean":
return (bool)value;
case "xsd:string":
return (string)value;
...
}
throw new UnknownTypeException();
}
【问题讨论】:
标签: c# xml linq-to-xml xmldocument xmlreader