【发布时间】:2018-10-03 18:35:54
【问题描述】:
我有一个返回一些 xml 的 Web 服务。没有对应的xsd。
我在 Visual Studio 中使用了选择性粘贴 -> 将 XML 粘贴为类功能来生成与 XmlSerializer 一起使用的类:
当代码执行该行时
--> XmlSerializer xmlSerialize = new XmlSerializer(typeof(table)); <--
table t = (table)xmlSerialize.Deserialize(new StringReader(soapResult));
它抛出一个异常:
System.InvalidOperationException: 'Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'string[]' to 'string'
error CS0029: Cannot implicitly convert type 'string' to 'string[]'
生成的类如下所示:
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class table
{
private string[] labelField;
private string[] classnameField;
private string[] datatypeField;
private string[][] rowField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("d", IsNullable = false)]
public string[] label
{
get
{
return this.labelField;
}
set
{
this.labelField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("d", IsNullable = false)]
public string[] classname
{
get
{
return this.classnameField;
}
set
{
this.classnameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("d", IsNullable = false)]
public string[] datatype
{
get
{
return this.datatypeField;
}
set
{
this.datatypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("d", typeof(string), IsNullable = true)]
public string[][] row
{
get
{
return this.rowField;
}
set
{
this.rowField = value;
}
}
}
问题出在行字段上,因为其他字段工作正常。 如果我改变了
[System.Xml.Serialization.XmlArrayItemAttribute("d", typeof(string), IsNullable = true)]
到
[System.Xml.Serialization.XmlArrayItemAttribute("d", typeof(string[]), IsNullable = true)]
错误消失了,但我的对象只有一个空字符串数组。
被反序列化的 XML 数据(为简单起见进行了压缩)如下所示
<?xml version="1.0" encoding="UTF-8"?>
<table>
<label>
<d>JobDefinition.SearchName</d>
<d>Job.JobDefinition</d>
</label>
<classname>
<d>JobDefinition.SearchName</d>
<d>Job.JobDefinition</d>
</classname>
<datatype>
<d>String</d>
<d>obj.JobDefinition</d>
</datatype>
<row>
<d>AB_DEFG_QA_RUN</d>
<d>A_JOB_Run</d>
</row>
<row>
<d>AB_DEFG_QA_RUN</d>
<d>B_JOB_Run</d>
</row>
</table>
【问题讨论】:
-
问题似乎与this answer 到How to serialize
List<List<object>>? 的最终更新 中描述的问题非常相似。
标签: c# xml xmlserializer