4

我有一个 XML,内容是

<Contracts>
    <Contract EntryType="U" ID="401" GroupCode="1">
    </Contract>
</Contracts>

我有一个带有合同清单的课程

[XmlArray("Contracts")]
[XmlArrayItem("Contract", typeof(Contract))]
public List<Contract> Contracts { get; set; }

所以当我尝试反序列化时,我收到了这个错误:

“反映属性‘合同’时出现错误。”

反序列化代码:

XmlSerializer reader = new XmlSerializer(typeof(ContractPosting));
xml.Position = 0;
eContractXML = (Contract)reader.Deserialize(xml);

以下是课程:

public partial class ContractPosting
{
    [XmlArray("Contracts")]
    [XmlArrayItem("Contract", typeof(Contract))]
    public List<Contract> Contracts { get; set; }
}

public class Contract
{
    [XmlAttribute(AttributeName = "ContractID")]
    public System.Nullable<int> ContractID { get; set; }

    [XmlAttribute(AttributeName= "PostingID")]
    public string PostingID { get; set; }

    public EntryTypeOptions? EntryType { get; set; }
} 
4

3 回答 3

3

可空类型不能序列化为属性。

您必须将Contract类更改为不Nullable用于 XML 属性,或者更改 XML 以将这些属性写入 XML 元素。

尝试这个:

public class Contract { 
  [XmlAttribute(AttributeName = "ContractID")] 
  public int ContractID { get; set; } 

  [XmlAttribute(AttributeName= "PostingID")] 
  public string PostingID { get; set; } 

  public System.Nullable<EntryTypeOptions> EntryType { get; set; } 
}

或者:

public class Contract { 
  public int? ContractID { get; set; } 

  [XmlAttribute(AttributeName= "PostingID")] 
  public string PostingID { get; set; } 

  public System.Nullable<EntryTypeOptions> EntryType { get; set; } 
}
于 2013-01-23T19:27:15.873 回答
0

谢谢,问题是 Nullable 类型,我以这种方式解决了

[XmlIgnore]
public System.Nullable<int> ContractID { get; set; }


[XmlAttribute("ContractID")]
public int ContractIDxml {
get { return ContractID ?? 00; }
set { ContractID = value; }
}
于 2013-01-24T13:34:37.607 回答
0

由于根节点是<Contracts>,请尝试将您的类重新安排为:

[XmlRoot("Contracts")]
public class ContractPosting {
    [XmlElement("Contract", typeof(Contract))]
    public List<Contract> Contracts { get; set; }
}

当您使用XmlArrayandXmlArrayItem时,它们都必须嵌套在某些东西中。但是你当前的XmlArray标签实际上是文件的根节点XML,所以它需要是一个XmlRoot.

演示:http: //ideone.com/jBSwGx

于 2013-01-23T19:07:01.620 回答