a...">

List deserialization error

I have XML, and the content

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

and I have a class with a list of contracts

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

so when i try to deserialize this i got this error:

"An error occurred reflecting the Contracts property.

Deserialization Code:

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

Here are the classes:

 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
source share
3 answers

Nullable types cannot be serialized as attributes.

You must either modify the Contract class to not use Nullable for XML attributes, or modify XML to write these properties as an XML element.

Try the following:

 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; } } 

OR

 public class Contract { public int? ContractID { get; set; } [XmlAttribute(AttributeName= "PostingID")] public string PostingID { get; set; } public System.Nullable<EntryTypeOptions> EntryType { get; set; } } 
+3
source

Since the root of the node is <Contracts> , try reinstalling your class on this:

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

When you use XmlArray and XmlArrayItem , they must be both inside and inside. But your current XmlArray tag is actually the root node of the XML file, so it should be XmlRoot .

Demo: http://ideone.com/jBSwGx

0
source

thanks, the problem was of type Nullable, and I solved in this way

 [XmlIgnore] public System.Nullable<int> ContractID { get; set; } [XmlAttribute("ContractID")] public int ContractIDxml { get { return ContractID ?? 00; } set { ContractID = value; } } 
0
source

All Articles