1

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>
user516883
  • 8,868
  • 23
  • 72
  • 114
  • http://stackoverflow.com/questions/4858798/datacontract-xml-serialization-and-xml-attributes/4859084#4859084 – jwaliszko Sep 22 '13 at 18:51
  • I am looking to deserialize not serialize, the example is perfect for serilizing the object. But I recieve this xml data and look to deserialize to a object – user516883 Sep 22 '13 at 19:27
  • I know, the case if it is serialization or deserialization is peripheral here. What matters is that attributes are not supported by `DataContract` API. You either have to use a class that implements `ISerializable` or use the `XmlSerializer`. The Data Contract Serializer used by default in WCF just doesn't support XML attributes (for performance reasons, as annotated in the link I've provided earlier). – jwaliszko Sep 22 '13 at 20:36

1 Answers1

2

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);
koffeinfrei
  • 1,985
  • 13
  • 19