Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

c# - XMLSerialize an ObservableCollection

I am having a problem in the xml serialization of observable collection.

Here is what I am serializing:

public enum Status { Pending, Active, Completed, Cancelled }

public abstract class Entity : INotifyPropertyChanged
{
    ...
}

public class UserStory : Entity
{
    public uint StoryID { get; set; }
    public Status Status { get; set; }
    ...
    public ObservableCollection<Task> Tasks { get; set; }
}

public class Task : Entity
{
    public uint TaskID { get; set; }
    ...
}

Here is how I serialize it:

public static void SerializeObjectToXML<T>(T item, string FilePath)
{
    XmlSerializer xs = new XmlSerializer(typeof(T));
    using (StreamWriter wr = new StreamWriter(FilePath))
    {
        xs.Serialize(wr, item);
    }
}

public class Main()
{
    ObservableCollection<UserStory> UserStories { get; set; }

    void Main()
    {
        ...
        ObservableCollection<object> Document = new ObservableCollection<object>();
        Document.Add(UserStories);
        SerializeObjectToXML<ObservableCollection<object>>(Document , "...");
        ...
    }
}

But an error occur in the xs.Serialize(wr, item); line saying:

InvalidOperation Exception: There was an error generating the XML document. Inner Exception: The type ScrumPresentor.ObservableCollection`1[[ScrumPresentor.UserStory, ScrumPresentor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context.

I am using Visual Studio 2010, WPF application in .NET 4.0.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using the System.Xml.Serialization.XmlInclude attribute. I'm not sure if I correctly understand your intent of a collection of collections, but assuming that is what you want, here is a working solution. The output follows the code:

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Xml.Serialization;

namespace StackoverflowXxmlSerialize
{

    public enum Status { Pending, Active, Completed, Cancelled }

    [System.Xml.Serialization.XmlInclude(typeof(UserStory))]
    [System.Xml.Serialization.XmlInclude(typeof(Task))]    
    public abstract class Entity : INotifyPropertyChanged 
    {
        public event PropertyChangedEventHandler PropertyChanged;
    }


    public class UserStory : Entity
    {
        public uint StoryID { get; set; }
        public Status Status { get; set; }
        public ObservableCollection<Task> Tasks { get; set; }
    }

    public class Task : Entity 
    {
        public uint TaskID { get; set; }
    }

    class Util
    {
        public static void SerializeObjectToXML<T>(T item, string FilePath)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (StreamWriter wr = new StreamWriter(FilePath))
            {
                xs.Serialize(wr, item);
            }
        }
    }



    public class TestSerialize
    {
        static ObservableCollection<Entity> UserStories { get; set; }

        public static void RunTest()
        {
            UserStories = new ObservableCollection<Entity> { 
                new UserStory  {
                StoryID = 127,
                Status = Status.Active,
                Tasks = new ObservableCollection<Task>{new Task { TaskID = 11 }, new Task { TaskID = 12 }}
                },

                new UserStory  {
                StoryID = 128,
                Status = Status.Cancelled,
                Tasks = new ObservableCollection<Task>{new Task { TaskID = 13 }, new Task { TaskID = 14 }}
                },

                new UserStory  {
                StoryID = 129,
                Status = Status.Completed,
                Tasks = new ObservableCollection<Task>{new Task { TaskID = 9 }, new Task { TaskID = 10 }}
                },
            };


            ObservableCollection<ObservableCollection<Entity>> Document
                = new ObservableCollection<ObservableCollection<Entity>>();

            Document.Add(UserStories);
            Util.SerializeObjectToXML<ObservableCollection<ObservableCollection<Entity>>>(Document, @"d:mpjunk.txt");

        }
    }

}

The above code produced this text file:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfArrayOfEntity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ArrayOfEntity>
    <Entity xsi:type="UserStory">
      <StoryID>127</StoryID>
      <Status>Active</Status>
      <Tasks>
        <Task>
          <TaskID>11</TaskID>
        </Task>
        <Task>
          <TaskID>12</TaskID>
        </Task>
      </Tasks>
    </Entity>
    <Entity xsi:type="UserStory">
      <StoryID>128</StoryID>
      <Status>Cancelled</Status>
      <Tasks>
        <Task>
          <TaskID>13</TaskID>
        </Task>
        <Task>
          <TaskID>14</TaskID>
        </Task>
      </Tasks>
    </Entity>
    <Entity xsi:type="UserStory">
      <StoryID>129</StoryID>
      <Status>Completed</Status>
      <Tasks>
        <Task>
          <TaskID>9</TaskID>
        </Task>
        <Task>
          <TaskID>10</TaskID>
        </Task>
      </Tasks>
    </Entity>
  </ArrayOfEntity>
</ArrayOfArrayOfEntity>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...