Is it possible to deserialize this XML into an object marked with the DataContract attribute?
<root> <distance units="m">1000</distance> </root>
As you may see there is "units" attribute. I don't believe that's supported. Or am I wrong?
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.
The DataContractSerializer fully supports this serialization programming model that was used by . NET Framework remoting, the BinaryFormatter, and the SoapFormatter, including support for the ISerializable interface. Types that represent raw XML or types that represent ADO.NET relational data.
Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.
This can be achieved, but you will have to override the default serializer by applying the [XmlSerializerFormat]
attribute to the DataContract. Although it can be done, this does not perform as well as the default serializer, so use it with caution.
The following class structure will give you the result you are after:
using ... using System.Runtime.Serialization; using System.ServiceModel; using System.Xml.Serialization; [DataContract] [XmlSerializerFormat] public class root { public distance distance=new distance(); } [DataContract] public class distance { [DataMember, XmlAttribute] public string units="m"; [DataMember, XmlText] public int value=1000; }
You can test this with the following code:
root mc = new root(); XmlSerializer ser = new XmlSerializer(typeof(root)); StringWriter sw = new StringWriter(); ser.Serialize(sw, mc); Console.WriteLine(sw.ToString()); Console.ReadKey();
The output will be:
<?xml version="1.0" encoding="utf-16"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <distance units="m">1000</distance> </root>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With