CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Threaded View

  1. #1
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    Serialization from Xml into Object

    First, I should state that this post refers to a Silverlight 4 application. Silverlight 4 seems to have a cut-down version of the Serialization model.

    I have an XML file in the following format:
    Code:
    <?xml version="1.0" standalone="yes"?>
    <TeamTable>
      <TeamRow Id="1" Name="Arsenal" />
      <TeamRow Id="2" Name="Aston Villa" />
      <TeamRow Id="3" Name="Blackburn Rovers" />
      <TeamRow Id="4" Name="Bolton Wanderers" />
      <TeamRow Id="5" Name="Chelsea" />
      ...
    </TeamTable>
    I read the XML into an XDocument and then call the Load(...) member on my TeamTable Class:
    Code:
        public class TeamTable : List<TeamRow>
        {
            public void Load(XDocument document)
            {
                foreach (XElement element in document.Descendants("TeamRow"))
                    this.Add(TeamRow.Load(element));
            }
        }
    For each of the TeamRow elements in the document, this function calls the Load(...) member of my TeamRow class:
    Code:
        [DataContract]
        public class TeamRow
        {
            [DataMember]
            public Int32 Id { get; set; }
    
            [DataMember]
            public String Name { get; set; }
    
            public TeamRow() { }
    
            public static TeamRow Load(XElement element)
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(TeamRow));
    
                using (XmlReader reader = element.CreateReader())
                {
                    return serializer.ReadObject(reader) as TeamRow;
                }
            }
        }
    All appears to be well, the first element passed to this function contains

    <TeamRow Id="1" Name="Arsenal" />

    as I would expect.

    However the ReadObject(...) function is throwing the following exception.
    Code:
    Expecting element 'TeamRow' from namespace 'http://schemas.datacontract.org/2004/07/...'..
     Encountered 'Element'  with name 'TeamRow', namespace".
    This is my first attempt at this type of serialization. Can anyone help me fix the exception?
    Last edited by rliq; May 23rd, 2010 at 08:54 PM.
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured