【发布时间】:2015-06-17 05:38:31
【问题描述】:
尝试将 xml 反序列化为 .NET 中的类时出错。 我获取了一个 xml 文件并使用 .net xsd 工具从中创建了一个 xsd,然后我从使用相同工具生成的 xsd 创建了类。
我得到这个异常:'对象不能存储在这种类型的数组中' 和“XML 文档 (8, 144) 中存在错误”。 在 xml 的那一行中,我得到了这个:
<events>
<event assist="" assistid="" extra_min="" id="21775794" minute="87" player="O. Atia" playerid="" result="[0 - 1]" team="away" type="goal"/>
</events>
这是生成的 c# 属性:
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("event", typeof(livescoreLeagueMatchEventsEvent), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public livescoreLeagueMatchEventsEvent[][] events {
get {
return this.eventsField;
}
set {
this.eventsField = value;
}
}
这是解析代码:
XmlSerializer deserializer = new XmlSerializer(typeof(T));
using (XmlReader reader = XmlReader.Create(path))
{
return (T)deserializer.Deserialize(reader);
}
这是生成的xsd:
<xs:element name="events" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="event" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="assist" type="xs:string" />
<xs:attribute name="assistid" type="xs:string" />
<xs:attribute name="extra_min" type="xs:string" />
<xs:attribute name="id" type="xs:string" />
<xs:attribute name="minute" type="xs:string" />
<xs:attribute name="player" type="xs:string" />
<xs:attribute name="playerid" type="xs:string" />
<xs:attribute name="result" type="xs:string" />
<xs:attribute name="team" type="xs:string" />
<xs:attribute name="type" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
我认为 xsd 工具正在创建正确的类结构,并且认为它可以在完全不更改代码的情况下工作。尝试进入序列化器反序列化方法没有任何成功...
【问题讨论】:
-
是什么自动生成的?顺便说一句,它是一个属性而不是一个类型......看看你的 xml 它不应该是一个二维数组,而是一个一维数组。
livescoreLeagueMatchEventsEvent[] -
我使用命令“xsd xmlfile.xml”从我的 xml 生成 xsd,然后使用命令“xsd xsdfile.xsd /classes”使用 XML Schema Definition Tool 从命令行。
-
你能显示 XSD 吗?生成代码中的多维数组是否正确? (我之所以问,是因为我记得 xsd.exe 中的一个错误,它在某些情况下产生了太多的数组维度。现在不记得具体细节了。)
标签: c# .net xml xml-deserialization