我创建了一个序列化为 xml 的对象:该对象的详细信息如下所示:
[XmlRoot(ElementName="trx")]
public class OTrx{
[XmlElement("body")]
public OBody Body {get;set;}
}
这是 OBody 类:
public class OBody {
[XmlElement("list")]
public Olist list {get;set;}
}
,类 Olist:
public class Olist {
[XmlAttribute("h")]
public string h {get;set;}
[XmlAttribute("colcnt")]
public string list {get;set;}
[XmlAttribute("list")]
public stringlist {get;set;}
[XmlElement("row")]
public List<ORow> RowList {get;set;}
}
类或行:
public class ORow{
[XmlElement("col")]
public List<OCol> ColList {get;set;}
}
类 OCol:
public class OCol{
[XmlText]
public string Text {get;set;}
public Ocol(string val){
this.Text=val;
}
}
这是我需要的输出:
<trx>
....
<body>
<list h="a,b,c,d,e" colcnt="5" rowcnt="5">
<row>
<col>value1</col>
<col>value2</col>
<col>value3</col>
<col>value4</col>
<col>value5</col>
</row>
<row>...</row>
<row>...</row>
<row>...</row>
<row>...</row>
</list>
</body>
</trx>
我调试代码,它显示列表中发生异常,当我注释该列表时,序列化成功,如下所示:
<row/><row/><row/><row/><row/><row/><row/><row/>
</list></body></trx>
请告诉我我哪里错了?
最佳答案
关于异常(exception)情况
Cannot serialize member 'ORow.ColList' of type '...', see inner exception for more details.
它说,在内部异常中(如所述):
OCol cannot be serialized because it does not have a parameterless constructor.
所以:添加一个无参数的构造函数:
public OCol() { }
或者只是删除显式构造函数,这可能更容易。
实际上,我认为您根本不需要 col
的类型 - 这应该适用于 ORow
:
public class ORow
{
[XmlElement("col")]
public List<string> Values { get; set; }
}
老实说,您的模型对于您的需求来说似乎过于复杂了。当不确定时,也许最务实的做法是复制你想要的 xml,然后使用编辑 -> 选择性粘贴 -> 将 XML 作为类粘贴,你会得到适合你想要的 xml 的东西(尽管通常可以显着清理)。
关于c# - 序列化列表对象为XML值异常: There was an error reflecting type "..Otrx",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53881202/