Reputation: 9378
I have a test xml file with data and setup my objects with the proper attributes. I am not getting any errors but none of the objects return with data after being deserilized. Thanks for any help.
[DataContract(Name = "level1", Namespace = "")]
public class Level1
{
[DataMember(Name = "level2")]
public Level2 Level2{get;set;}
}
[DataContract(Name = "level2", Namespace = "")]
public class Level2
{
[DataMember(Name = "code")]
public string Code{get;set;}
[DataMember(Name = "global")]
public string Global{get;set;}
}
//Desrilizing Data
DataContractSerializer dcs = new DataContractSerializer(typeof(Level1));
FileStream fs = new FileStream("ExampleData/Example.xml", FileMode.OpenOrCreate);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
Level1 p = (Level1)dcs.ReadObject(reader);//Coming back but with no values
XML
<?xml version="1.0" encoding="utf-8" ?>
<level1>
<level2 code="332443553" global="21332"/>
</level1>
Upvotes: 1
Views: 1635
Reputation: 2045
The properties of level2
are expected to be xml elements, not xml attributes:
<?xml version="1.0" encoding="utf-8" ?>
<level1>
<level2>
<code>332443553</code>
<global>21332</global>
</level2>
</level1>
EDIT
To deserialize with the attributes, you have to use XmlSerializer
instead of the DataContractSerializer
, as stated above in the comments:
// Attribute on Property
[DataMember(Name = "code"), XmlAttribute]
public string Code{ get; set; }
// ...
// Deserialization
XmlSerializer serializer = new XmlSerializer(typeof(Level1));
// ...
Level1 p = (Level1)serializer.Deserialize(reader);
Upvotes: 2