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

Top 5 Contributors of the Month
Melody Anderson
Post New Web Links

XmlSerializer and IList

Posted By:      Posted Date: October 18, 2010    Points: 0   Category :.NET Framework
Has someone found any workaround for this bug? It looks like the XmlSerializer cannot serialize a member of type IList<T>.

public class Program
    public class Order { }
    public class User
        private IList<Order> _orders;
        public IList<Order> Orders
            get { return _orders; }
            set { _orders = value; }

    static void Main(string[] args)
        User user = new User();
        user.Orders = new List<Order>();
        user.Orders.Add(new Order());

        XmlSerializer serializer = new XmlSerializer(typeof(User));
        serializer.Serialize(Console.Out, user);

The DataContractSerializer used in WCF handles correctly members of this interface but I am using it in a classic web service which uses XmlSerializer. Declaring the member as List<T> instead of IList<T> is not a solution for me.

Any suggestions are greatly appreciated,


View Complete Post

More Related Resource Links

How to access the refrenced table fields in Ilist object of table MVC asp.net



I have 2 tables, master, detail. 1.master table have fields (id, username, plan)-->id is primary key (PK) 2. detail table have fields (srNo,id, worksummary, ... )--> srNo is PK.

I have created foreign key relationship from detail to .master table for "id" field.

the code is:

IList<detail> objDetail=new List<detail> (); 
IList<master> objMaster = new List<master> ();
string[] sarray = queryFields.Split('|');//

for (int i = 0; i < sarray.Length; i++)
string[] sfields = sarray[i].Split(',');

if (sfields[0] != "")

objDetail.Add(new _detail { Id = count , modify = sfields[1].ToString(), verified = sfields[2], I});


I have problem to add fields in "objDetail" using Add method. But I am unable to access the reference field "Id" , rest of the field of detail table can be accessed using objDetail.

How can I access the "Id" field from objDetail object to add in IList.

I want to solve this problem

XmlSerializer - how to define class to not generate attributes in root element?

Hi! I have simple class that I serialize to xml file: <?xml version="1.0" encoding="utf-8"?> <MyRootElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Area="East">   <Products>     <SalesProduct Taxable="true">       <Name>Sofa</Name>     </SalesProduct>     <Product>       <Name>Television</Name>     </Product>   </Products> </MyRootElement> I don`t want have in xml file attributes xmlns:xsi and xmlns:xsd. How can I define class to not have these two attributes in xml file? I tried use XmlRoot attribute but there is no control for these two attributes. They are always generated. Regards

XMLSerializer don't handle mixed contents properly

mixed content model allows a combination of text and elements in the XML document. we use .net xmlserializer to serialize/deserialize the XML. XmlSerializer don't handle mixed content properly. XmlSerializer handles mixed content models to a degree. XmlSerializer add the text in the xml document, but the position of text is not exactly where they appeared in the original XML document. Let's take a example here is original xml <employee xmlns="http://example.org/xmlserializer">   here is some text...   <id>333-33-3333</id>   here is some more...   <name>Bob Smith</name>   and here is even more... </employee> We deserialize above xml using the xmlserializer then we serialize it back into xml. Now xml document is changed as follows <employee xmlns="http://example.org/xmlserializer">    <id>333-33-3333</id>   <name>Bob Smith</name>   here is some text...   here is some more...    and here is even more... </employee> You see the position of text is changed. I have seen the Microsoft code to serialize/deserialize the xml through reflector. They put text in a string array but position is not saved. Is there any solution or workaround? I don't want to parse the xml by xmlReader. I want fix in the Microsoft generated classes that ar

XmlSerializer crashes when vb6 instantiates it via COM

I Have a vb6 application that uses .net clases via COM. When one of this clases calls code which instantiates XmlSerializer vb6 aplication crashes. Just this line fails: Dim x as new XmlSerializer(GetType(CustomClass)) I agregate that these clases load assemblies dinamically but only it crashes over vb6 aplication. In .net 100% aplication this not happens. I don't know if this is the forum I should post this problems Thanks for your help.

Can serialize but not deserialize class containing an xs:list attribute using XmlSerializer

I have a simple serializable class along the lines of: [Serializable] [XmlType] public class MyClass { [XmlAttribute("values")] public int[] Values { get; set; } } If I create an instance of this class with Values set to an empty collection the XmlSerializer class produces this output as expected: <?xml version="1.0" encoding="utf-16" ?> <MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" values="" /> However, deserializing this exact output throws a System.FormatException: Input string was not in a correct format. Shouldn't the XmlSerializer be able to deserialize this, since it produced the xml string in the first place?

IEnumerable instead of IList or Collection

hi,Just wondering and see what your opinions are.I usually pass around the layers either a Custom Collection<T> or a Custom ListBase<T>:IList ..I was now wandering if instead of return from a Data Access Layer or biz layer one of those is better to actually just return an IEnumerable<T>.Shall I drop returning all those LIst<T> Collection<T> and use IEnumerable<T> instead?Would that be more flexible?Thanks for any suggestionsThanks for your help

Nesting serialized classes with XmlSerializer without escaped brackets

Hi The company I work for use a state implementation based on the XmlSerializer generic class in so far that we have state classes with simple public variables and no logic which we then use the XMLSerializer to serialize in in great extend nest. For instance class A has a Class B and a class C variable, each with a state class being serialized and put into a state class of the owner class. Is there any way outside actually implementing IXmlSerializable that I can allow to include XML directly in own output xml instead of escaping it when it meets brackets in strings for instance? The deal is that since all state classes individually are serialized simple classes, I know that they contain valid XML and that that will conform to the XMLDOM even if piecing them together and manually implementing the serializers will be quite time consuming even if limiting to the CSharp framework, but the multi layer escaped structure is awfull to the eye. See this simplified example: using System.Xml; using System.Xml.Serialization; using System; using System.IO; namespace TingTester { class Program { static void Main(string[] args) { var simpleser = new XmlSerializer(typeof(LittleStateClass)); string serialized = Serialize(GetSimpleVersion(), simpleser); Console.WriteLine("Simple elements contain no escapes: {0}", !serialized.Contains("&"

Cannot Implicitly Convert Type Ilist to List

Hi All, In the below code i get the Following Error, Cannot implicitly convert type 'System.Collections.Generic.List<Nous.nSpeckEnterprise.GetEnterpriseComponent_Result>' to 'System.Collections.Generic.IList<Nous.nSpeckEnterprise.Component>'. An explicit conversion exists (are you missing a cast?)   <br/> NSTTT_CRRISQ_TESTEntities entities = new NSTTT_CRRISQ_TESTEntities();<br/> IList<Component> Components = new List<Component>();<br/> var c = entities.GetEnterpriseComponent(componentId).ToList();<br/> <strong>Components = c;<br/> </strong> return Components;   Can anyone help me how to do teh cast.......Thanks  

XmlSerializer: Serialize an array of System.Drawing.Color

Ok,  here is my problem... I am building a UI configuration tool that utiliizes a PropertyGrid.  One of the properties is a indexed list of Colors contained in an array: CategoryAttribute("Style"), DisplayName("Data Set Colors"), DescriptionAttribute(""), XmlArray("SetColors"), XmlArrayItem(ElementName="Color",Type=typeof(SColor))] public Color[] SetColors { get; set; } The beauty of the PropertyGrid is it knows how to handle this Poperty and properly handles array and list of Colors. BUT...   As we already know in order to serialize a Color,  we have to use a surrigate property,  which is very unfortunate, and I fear is one of those little thing MS just overlooked.  (I understand it is actually a structure and not a class and has not default properties from which to get type info from.) I am really amazed that when I do serialize the class,  the XML is soooo  close to what I need,  its just missing the actual color value data: <AppGridColumnConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name>Label</Name> <SetColors> <Color /> <Color /> <Color /> </SetColors> <IsDefaultEditable>false</IsDefaultEditable> <IsDirtyCheck&

Problems with XmlSerializer and namespace

Hi, I am not sure if this is a bug or I am missing something obvious, but I'm having difficulty adding a default namespace when serializing an object using the XmlSerializer.Serialize() function. I am supplying the namespace with an XmlSerializerNamespaces object to the Serialize() function but it just seems to get ignored. Here is the code I am using with a simple example object called Car [Serializable()] public class Car { public Car() { } private string _color; public string Color { get { return _color; } set { _color = value; } } private int _doors; public int NumberOfDoors { get { return _doors; } set { _doors = value; } } private string _model; public string Model { get { return _model; } set { _model = value; } } private string _manufacturer; public string Manufacturer { get { return _manufacturer; } set { _manufacturer = value; } } } And here is the code that I am serializing to a string: //Example namespace to use string nmspace = "http://www.mynamespace.com/Car"; StringBuilder xmlString = new StringBuilder(); StringWriter sw = new StringWrite

Can XmlSerializer add attributes to an element?

I'm using XmlSerializer to serialise a c# object into XML.public class Letter{        [XmlElement]        public String AccountNumber { get; set; }}which gives:<Letter><AccountNumber>12345678</AccountNumber></Letter>What I'd like to be able to do is to add a flag as an attribute to say if the particular data element is encrypted, so the XML comes out as:<Letter> <AccountNumber encrypted="true">=S2Hgd3$eDF</AccountNumber> </Letter>Is it possible to add this encrypted flag easily using the XmlSerializer? Thanks for any advice!

iList Application


Hi, I am trying to figure out and create one very interesting aplication using asp.net and sql server.

I would like to create web application to generate a Lists, lists with different atributes, so when my user visit

my page he is already loged in and he try to create a list, he defines the atrbutes and write them if he wants.

He also can delete atrubutes from list or delete a list... and so on

So if You have any idea for me or you can help please do so.

My major problem is how to create a list, I am thinking in using asp.net mvc, but I don't know what would be best way.


IList IsFixedSize property


When looking at MSDN (http://msdn.microsoft.com/en-us/library/system.collections.ilist.isfixedsize.aspx), the definition for IsFixedSize is:

"A collection with a fixed size does not allow the addition or removal of elements after the collection is created, but it allows the modification of existing elements."

However, the example given on the same page has:

public bool IsFixedSize { get { return true; } }

which appears contradictory as the methods Add/Remove/RemoveAt are functional and the property Count is variable, implying IsFixedSize should be false. Is this an error in the documentation, or where can I find a more precise definition of this property?


MessageContract/XMLSerializer - Known Type not being named with its element name when passed as obje


Okay, I've just deleted my first post since I was having issues with editting a post with codeblocks.  Trying once more.

I'm new to WCF and I am trying to write a webservice that must follow a specific XML format.  Because of this, I found that I had to drop DataContractSerializer since I must be able to use attributes.  I now have the <XMLSerializerFormat> attribute on my servicecontract for this purpose and I have laid out the schema I need by using a Class with Public Properties and the <Serializable()> attribute where appropriate.  I have one service endpoint that has several different schemas that it may accept.  I have a base class with derived classes for this purpose.  This also works well from what I can see as the test client and webservice are talking to each other just fine.  However, the client that will be using the service is non-WCF and must have the elements named specifically in order to handle them.  The problem arises when the service is serializing the derived classes.  The structure of each class works perfectly, however, the name of the element is not the name of the element I have assigned it.  It is most likely because of the way that I pass the information back and forth to the service and the fact that I do not know what the object actually is when it is passed into or out o

XmlSerializer E|rror

on ReportServer Class

XmlSerializer serializer = new XmlSerializer(typeof(Report))

ther is an error
System.InvalidOperationException was unhandled
InnerException: System.NotSupportedException
Message=Cannot serialize member Microsoft.ReportingServices.RdlObjectModel.Report

(c# 2010 Sql server R2)


'ToList' is not a member of 'System.Collections.IList'



I am trying to cast a collection of IList object but why I get this error message "'ToList' is not a member of 'System.Collections.IList'"

The DataRecords1() function below works but not the DataRecords2() function.

Public Function DataRecords1() As IList

Dim dataInformation = From xyz In _DBContextTable1

Return dataInformation.ToList() 'works
End Function

Public Function DataRecords2() As IList
Dim dataInformation As IList

dataInformation = From xyz In _DBContextTable1

Return dataInformation.ToList() 'not working Sad
End Function



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