I have a simple XML document that I want to read into an object using the DataContractSerializer in .NET.
<Person>
<Enabled>true</Enabled>
<Name>John Smith</Name>
</Person>
When I read the object, the Enabled field is always false even though the node value is "true." How does one define XML that will probably deserialize into a boolean true when ReadObject() is called?
It all depends on how you define your class. If you define it as follows, it should read correctly.
public class StackOverflow_8012009
{
const string XML = "<Person><Enabled>true</Enabled><Name>John Smith</Name></Person>";
[DataContract(Namespace = "", Name = "Person")]
public class Person
{
[DataMember]
public bool Enabled { get; set; }
[DataMember]
public string Name { get; set; }
public override string ToString()
{
return string.Format("Person[Enabled={0},Name={1}]", this.Enabled, this.Name);
}
}
public static void Test()
{
DataContractSerializer dcs = new DataContractSerializer(typeof(Person));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
object obj = dcs.ReadObject(ms);
Console.WriteLine(obj);
}
}