Tuesday, 2 December 2014

serializing sequence of item using DataContractSerializer



is there a way to unserialize/serialize the following xml by using DataContractSerializer.



<?xml version="1.0" encoding="utf-8"?>
<test xmlns:xsi="http://ift.tt/ra1lAU" mlns:xsd="http://ift.tt/tphNwY">
<id>someId</id>
<st>s1</st>
<st>s2</st>
</test>


this xml is given by the XmlSerializer part of following code



using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;

namespace cledes {
class Program {
static void Main(string[] args) {
TEST t = new TEST {
Id = "someId",
Sts = new List<String> {"s1", "s2"}
};
DataContractSerializer dcs = new DataContractSerializer(typeof(TEST));
XmlSerializer xs = new XmlSerializer(typeof(TEST));
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true; xws.Indent = true;

XmlWriter xw = XmlWriter.Create(Console.Out, xws);
dcs.WriteObject(xw, t);
xw.Flush();
Console.WriteLine();
Console.WriteLine(" ===== ===== =====");
xs.Serialize(Console.Out, t);
Console.WriteLine();
}
}

[XmlRoot("test")]
[DataContract(Name = "test", Namespace = "http://test.cledes")]
public class TEST {
[XmlElement("id")]
[DataMember(Name= "id")]
public String Id { get; set; }
[XmlElement("st")]
[DataMember(Name = "st")]
public List<String> Sts { get; set; }
}
}


the DataContractSerializer part gives



<test xmlns:i="http://ift.tt/ra1lAU" xmlns="http://test.cledes">
<id>someId</id>
<st xmlns:d2p1="http://ift.tt/1bQEByM">
<d2p1:string>s1</d2p1:string>
<d2p1:string>s2</d2p1:string>
</st>
</test>


Here List<String> is just a sample. In my real case it is a List<ComplexType>.


I knew about CollectionDataContract but after googling a little, my guess is that DataContract does not allow to serialize:



<xsd:complexType name="test">
<xsd:sequence>
<xsd:element name="somId" type="string25" minOccurs="1" maxOccurs="1" />
<xsd:element name="st" type="string25" minOccurs="1" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>


for example scvutil.exe reports that unbounds should be 1.


M I right (about inadaptation of DataContract to this case) or not ?


If I'm wrong, any clue is welcome (PS: I'm trying to keep XmlSerializer and DataContractSerializer).


No comments:

Post a Comment