c# - 将列表对象序列化为 XML 值异常:反映类型“..Otrx”时出现错误
问题描述
我创建了一个用于序列化为 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;}
}
ORow 类:
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>
请告诉我我错了什么?
解决方案
在关于异常的下面
无法序列化类型为“...”的成员“ORow.ColList”,有关详细信息,请参阅内部异常。
它说,在内部异常中(如前所述):
OCol 无法序列化,因为它没有无参数构造函数。
所以:添加一个无参数的构造函数:
public OCol() { }
或者只是删除显式构造函数,这可能更容易。
col
实际上,我认为您根本不需要 for 类型- 这应该适用于ORow
:
public class ORow
{
[XmlElement("col")]
public List<string> Values { get; set; }
}
不过老实说,您的模型似乎过于复杂,无法满足您的需求。当不确定时,也许最务实的做法是复制您想要的xml,然后使用 Edit -> Paste Special -> Paste XML As Classes,您会得到适合您想要的 xml 的东西(尽管通常可以清理显着上升)。
推荐阅读
- .net-core - 带有 MSAL 登录的 Microsoft Teams 选项卡
- nginx - 如何在地图中使用 nginx 正则表达式来提取 json 中键的值
- r - 将数据框字符串列拆分为多列而不使用模式
- javascript - 将嵌套数组转换为 HTML 结构
- python - 创建一个函数来获取 s 形曲线的值
- android - Android 画中画模式
- odoo-13 - odoo13 错误创建新产品公共类别(电子商务)
- azure-devops - 在 Azure DevOps Services 管道中安装 Terraform 时出现自签名证书错误
- azure - Azure App Service Kudu 工具“LogFiles”自动删除——容器应用服务(linux)
- quantum-computing - 为什么量子计算机中的恒定运算需要第二个 qbit?