首页 > 解决方案 > 将列表对象序列化为 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>

请告诉我我错了什么?

标签: c#.netxmlserialization

解决方案


在关于异常的下面

无法序列化类型为“...”的成员“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 的东西(尽管通常可以清理显着上升)。

在此处输入图像描述


推荐阅读