.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

XML Deserialization

Posted By:      Posted Date: September 23, 2010    Points: 0   Category :ASP.Net

I am Trying to deserialize an xml file and loop through the deserialzed objects. Here is my code:

using System.Xml.Serialization;
using System.Collections;
using System.Collections.Generic;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Departments : IEnumerable<Department>

    private Department[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Department", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public Department[] Items
            return this.itemsField;
            this.itemsField = value;

    #region IEnumerable<Department> Members

    public IEnumerator<Department> GetEnumerator()
        for (int i = 0; i < itemsField.Length; ++i)
            yield return itemsField[i];


    #region IEnumerable Members

    IEnumerator IEn

View Complete Post

More Related Resource Links

Json Deserialization is giving error in IronPython



Have anyone tried json deserialization. When I tried:

>>> import json

>>> json.loads('["foo", {"bar":["baz", '"Test", 1.0, 2]}]')

I got following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\IronPython 2.6 for .NET 4.0\Lib\json\__init__.py", line
 307, in loads
  File "C:\Program Files\IronPython 2.6 for .NET 4.0\Lib\json\scanner.py", line
42, in iterscan

.NET Matters: Deserialization Progress, and More


Build a standard progress bar that indicates how much deserialization has completed and how much still remains. Plus, System.Collection.Generics performance.

Stephen Toub

MSDN Magazine December 2006

Deserialization Error PropertyChangeEvent



I have a WebServiceHost which redrieves Data out of a . I have CommonDLL for all Properties. I used an ObjectBase Class with the inheritance in the common class. (with Implements InotifyPropertyChange and IDataErrorInfo). (This is Host side)

TheClient is a Web Padge which is showing data. Works fine. Except, if I do a ServiceReference update , I get a Compiler error: 

Public Property PropertyChangedEvent() As System.ComponentModel.PropertyChangedEventHandler Get Return Me.PropertyChangedEventField property 'PropertyChangedEvent' conflicts with a member implicitly declared for event 'PropertyChanged' in class 'ObjectBase'  in the Reference.vb

Now I was going to put more funcionallity to the Client ADD and UPDATE Data!

I recieving Now an Error Message while trying to add new Data:

 The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:Fahrz. The InnerException message was 'Error in line 1 position 369. 'Element' '_error' from namespace 'http://schemas.datacontract.org/.....Common' is not expected. Expecting element 'PropertyChangedEvent'.'. Please see InnerException for more details.

Deserialization issue with returned from web service

Hi, I have a VS 2008 C#  client using a proxy generated by the Service Reference tool from a schema for a (prob Java?) ASMX web service.  I got serialisation errors when I tried connecting to the service around<xs:date> date fields, and on inspecting the incoming XML discovered the date format was yyyy-mm-dd hh:mm:ss.sss.   So 2 questions really.. 1) Is the schema I've been supplied with incorrect? 2)Is there a way to work around this, apart from manually editing the schema to xs:datetime and regenerating the classes?   Thanks MJ

DataContractSerializer deserialization puzzle - by-pass member initialization.

Hi, I was using WCF and during the transmission of a object, of the type Book, see code below, the deserialization process throws a NullReferenceException. To isolate the problem, I uses a unit test like this rather than involving the full blown WCF marshalling. This appears to be solely a serialization/deserialization problem and has nothing to do with the communication issues in WCF. [Test] public void TestSerializeAndDeserializeBook() {     Book book = new Book( "Testing Serialization and Deserialization",                         new Person( 100, "Tom", "Smith" ),                         new Person( 101, "Peter", "Pan" ) );     DataContractSerializer ser = new DataContractSerializer( typeof(Book) );     using( Stream stm = new MemoryStream() )     {         ser.WriteObject( stm, book );         stm.Seek( 0, SeekOrigin.Begin );         Book regen = ser.ReadObject( stm ) as Book; // NullReferenceException here     &nb

handle missing types during deserialization

I have situations where I may have a type reference in the object graph that is no longer available because it has been depricated. These are objects defined outside the control of my serialization API. I need the deserializer to just ignore these objects and move on without erroring out with: "Unable to find assembly 'MyMissingAssembly, Version=, Culture=neutral, PublicKeyToken=null'." My question is not why the error is occuring. I understand why. But how do I handle this error gracefully, have the missing types skipped, and continue deserializing the rest of the object graph? I have experimented returning a dummy class through the VersionDeserializationBinder.BindToType() method so that I can do type substitution with types I control. This works but I need a way to discriminate for which types I should do this for. So I need to know if the deserializer has access to the type in question before it attemts to deserialize the object. If only it could tell me it can't find it before it throws the error.  

Testing JSON Deserialization

Hi all, Apologies for x-posting - I started here a week ago http://forums.asp.net/p/1112792/1718323.aspx#1718323 but haven't had any responses - so I'm hoping this is a better place.. :) I'm not using a webservice, I am just using the JavaScriptSerializer class within System.Web.Script.Serialization to serialise a complex object into a string (which works fine...) then use the same string to deserialize it back into the original object, which fails with the below error The value "System.Collections.Generic.Dictionary`2[System.String,System.Object]" is not of type "OrYx.TVShopping.TVScriptsTestHarness.Person" and cannot be used in this generic collection.Parameter name: value JSON string following serialization: "{\"Teacher\":\"Bugs\",\"Students\":[{\"Name\":\"Snoopy\",\"Birthday\":\"\\/Date(66661200000)\\/\",\"Age\":35},{\"Name\":\"Fred Bassett\",\"Birthday\":\"\\/Date(314888400000)\\/\",\"Age\":28}]}" My system: WinXP, .NET 2.0, AJAX ASP.NET RC1  The class being serialised (ClassRoom) contains a Dictionary class (Students).  It seems to get confused when trying to cast the dictionary (Students) object.  Aside: Serializing and deserializing objects containing only simple types (

Other name than ArrayOf for XML deserialization of list

Hi  I deserialize a list from app.config. When I use the tag name ArrayOfProfile it works, but I would like to call it ProfileList instaed. I know that deserialization responds to the ArrayOf prefix, but can I change this? I am not interested in wrapping it in root element (been there) and in my context I cannot use [XmlArray("ProfileList ")] TIA Best regards Søren

Other name than ArrayOf for XML deserialization of list

Hi  I deserialize a list from app.config. When I use the tag name ArrayOfProfile it works, but I would like to call it ProfileList instaed. I know that deserialization responds to the ArrayOf prefix, but can I change this? I am not interested in wrapping it in root element (been there) and in my context I cannot use [XmlArray("ProfileList ")] TIA Best regards Søren

incorrect deserialization of webservice response

Hi,   I am trying to consume an axis2 webservice from a .NET CF platform. The development platform is Visual Studio 2008 . I have pasted the wsdl , sample response from webservice , for the getEpcByAttribute method.  On execution I initially got a Invalid Cast exception (details below):  System.InvalidCastException was unhandled   Message="InvalidCastException"   StackTrace:        at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length) On further investigation it seemed like the generated file (Reference.cs) had a two dimensional array, which the xmlserializer was trying to put the response into, and was failing. I tried to modify the generated file by converting the 2 dimensional array to a 1 dimensional array . The SOAP call was going through now, but the de-serialization was incorrect. Only the first row of the response was getting de-serialized. I have pasted relevant section from the Reference.cs below. Is there any workaround/fix for this problem (apart from modifying the webservice). Thanks.   WSDL: ---------- <?xml version="1.0" encoding="UTF-8"?> <wsdl:definitions targetNamespace="urn:JDVisiblEdgeService" xmlns:axis2="urn:JDVisiblEdgeService" xmlns:ns1="http://vo.proj

NetDataContractSerialization throwing deserialization error

hi, I have methods which return interface and some methods which accepts interface as parameters. I am trying to use Net DataContractSerializer but I am getting following error... The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:id. The InnerException message was 'Error in line 1 position 120. XML 'Element' 'http://tempuri.org/:id' does not contain expected attribute 'http://schemas.microsoft.com/2003/10/Serialization/:Type'. The deserializer has no knowledge of which type to deserialize. Check that the type being serialized has the same contract as the type being deserialized.'. Please see InnerException for more details. Please help me how to resolve this error.... If I use Netdatacontract attribute on Operation Contract, can i use DataContract and Datamember attribute on serializable class??? Thanks in advance...

SAML Token Deserialization Performance


I have an IDispatchMessageInspector which is deserializing a SAML Token contained in the SOAP message header.

To do the deserialization I am using the following code:





List<SecurityToken> tokens = new List<SecurityToken>();

tokens.Add(new X509SecurityToken(CertificateUtility.GetCertificate()));

SecurityTokenResolver outOfBandTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection<SecurityToken>(tokens), true);

SecurityToken token = WSSecurityTokenSerializer.DefaultInstance.ReadToken(xr, outOfBandTokenResolver);

The problem I am seeing is that the performance of the ReadToken call varies depending on the account that is running the windows service (in which the WCF service is hosted).

If the service is running as a windows domain account the elapsed time for the ReadToken call is virtually zero. When running as a local machine account the call takes about 1 second.


Can anyone shed any light on what is going on here and why the account running this bit of code makes a difference as to its performance?


XML Deserialization


I am Trying to deserialize an xml file and loop through the deserialzed objects. Here is my code:

view plain

Xml deserialization of a Nullable DateTime object


Morning, we've had this a lot but the answers I've found do not appear to work.


C# 3.0, .Net 3.5, XML Serialization into a nullable DateTime property does not work with an empty string.  The exception is thrown before the internals of the property, when the XmlSerializer attempts to use DateTime.ParseExact (when I use a DataType="date" value) and just complains that it is not a valid DateTime format when I do not.

A few of the various combinations of signature that I have used are below but am I fundamentally wrong that empty strings should be classed as null values?  I bet at the end of this the conclusion will be: "if you have a value then pass a populated element in the xml, if you don't then don't pass that element at all" or "if you have no value you can still send the element so long as it has the xsi:nil attribute" .

A few combinations:


DateTime Foo {get; set;}



DateTime? Foo {get; set;}


[XmlElement("foo", DataTime="date")] // yes I just want the date part

DateTime? Foo {get; set;}


[XmlElement("foo", IsNullable=true)] // I believe Bet that this onl

Serialization and deserialization over network is very slow


I am using the built in C# serialization and deserialization functionality to pass objects over network streams and it works fine. The problem iswhen the client and server programs are running on different computers, sending even the simplest objects over the pipe using serialization is painfully slow (about 50x slower than using byte arrays). If I have the client running on the same box as the server, the serialization approach is nearly as fast as the byte array approach (even though network sockets and serialization are still used). It only slows down when the client and server are running on different machines. Clearly, Serialization is not the cause of the slow down. So why is it so much slower than the byte array approach when the server and client are not on the same computer? Thanks for any help. 


I have put together a simple client/server program to demonstrate this oddity:

namespace PingTest {
 class Server {
  public static void Start() {
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binFormatter =
     new System.Runtime.Serialization.Formatters.Binary.Binar

Deserialization and SOAP envelope

I've created a web service that handles a fairly complex xml request. The service uses classes that I auto-generated from the xsd to deserialize the xml. I now need handle xml requests that have SOAP envelopes. I've tried SoapReflectionImporter but it is throwing an exception 'type System.Xml.XmlElement may not be serialized with SOAP message' which is referring to collections in my auto-generated classes. Is there any way to add this functionality without having to rewrite the auto-generated classes?

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend