c# - Deserialize using DataContractSerializer -


i trying deserialize xml file looks following

<?xml version="1.0"?>  <test xmlns:i="http://www.w3.org/2001/xmlschema-instance" xmlns="http://schemas.datacontract.org/2004/07/consoleapplication6">    <values>      <string>value 1</string>      <string>value 2</string>    </values>  </test>

to object this

[datacontract(namespace = "http://schemas.datacontract.org/2004/07/consoleapplication6")] public class test {     [datamember(name = "values")]     public string[] values; } 

with

var ds = new datacontractserializer(typeof(test));         using (stream stream1 = file.openread(@"c:\projects\test1.xml"))         {              test rr = (test)ds.readobject(stream1);         } 

however none of values deserializing. see , empty array in test rr. please tell doing wrong. in advance.

if need fine control of xml emitted when serializing, should not use datacontractserializer. has limited flexibility. better off using xmlserializer, has liimtitations well, more flexible datacontractserializer.

that being said, here how can want datacontractserializer.

change default namespace on xml use 1 datacontractserializeruses default.

<?xml version="1.0"?> <test xmlns:i="http://www.w3.org/2001/xmlschema-instance" xmlns="http://schemas.datacontract.org/2004/07/">   <values>     <string>value 1</string>     <string>value 2</string>   </values> </test> 

instead of using string[] create own custom type derives list<string>. must done solely purpose of having hang collectiondatacontractattribute on. collectiondatacontractattribute let specify name of elements inside <values>.

[datacontract] public class test {     [datamember(name = "values")]     public testvalues values;  }  [collectiondatacontract(itemname = "string")] public class testvalues : list<string> { } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -