Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataContract XML serialization and XML attributes

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?

like image 437
Schultz9999 Avatar asked Feb 01 '11 04:02

Schultz9999


People also ask

What is XML serialization?

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.

What is DataContract attribute?

[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.

Which of the following forms of serialized XML is supported by the DataContractSerializer?

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.

What is the difference between binary serialization and XML serialization?

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.


1 Answers

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> 
like image 54
Greg Sansom Avatar answered Sep 16 '22 16:09

Greg Sansom