0

我使用 XML 序列化制作了一个 xml 文档。

看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<Course xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <courseName>Comp 1510</courseName>
  <backgroundColor>#ffffff</backgroundColor>
  <fontColor>#ffffff</fontColor>
  <sharingKey>ed35d1f8-6be1-4f87-b77f-c70298e5abbb</sharingKey>
  <task type="Assignment">
    <taskName>First Task</taskName>
    <description>description</description>
    <taskDueDate>2010-01-24T12:41:20.0321826-08:00</taskDueDate>
    <weight xsi:nil="true" />
    <beforeDueDateNotification>30</beforeDueDateNotification>
    <outOf>50.4</outOf>
  </task>
</Course>

我的代码来做这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    [XmlRoot("Course")]
    public class MyWrapper 
    {
        public MyWrapper()
        {
            TaskList = new List<Tasks>();
        }

        [XmlElement("courseName")]
        public string CourseName { get; set; }

        [XmlElement("backgroundColor")]
        public string BackgroundColor { get; set; }

        [XmlElement("fontColor")]
        public string  FontColor { get; set; }

        [XmlElement("sharingKey")]
        public Guid SharingKey { get; set; }

        [XmlElement("task")]
        public List<Tasks> TaskList { get; set; }

    }

public class Tasks
{
    [XmlAttribute("type")]
    public string Type { get; set; }

    [XmlElement("taskName")]
    public string TaskName { get; set; }

    [XmlElement("description")]
    public string Description { get; set; }

    [XmlElement("taskDueDate")]
    public DateTime TaskDueDate { get; set; }

    [XmlElement("weight")]
    public decimal? Weight { get; set; }

    [XmlElement("beforeDueDateNotification")]
    public int BeforeDueDateNotification { get; set; }

    [XmlElement("outOf")]
    public decimal? OutOf { get; set; }

}

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            MyWrapper wrap = new MyWrapper();
            wrap.CourseName = "Comp 1510";
            wrap.FontColor = "#ffffff";
            wrap.BackgroundColor = "#ffffff";
            wrap.SharingKey = Guid.NewGuid();

            Tasks task = new Tasks()
            {
                TaskName = "First Task",
                Type = "Assignment",
                TaskDueDate = DateTime.Now,
                Description = "description",
                BeforeDueDateNotification = 30,
                OutOf = 50.4M
            };

            wrap.TaskList.Add(task);
            SerializeToXML(wrap);

           var grab = DeserializeFromXML();

           foreach (var item in grab)
           {

           }
        }

        static public void SerializeToXML(MyWrapper list)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper));
            TextWriter textWriter = new StreamWriter(@"C:\New folder\test.xml");
            serializer.Serialize(textWriter, list);
            textWriter.Close();
        }

        static List<MyWrapper> DeserializeFromXML()
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(List<MyWrapper>));
            TextReader textReader = new StreamReader(@"C:\New folder\test.xml");
            List<MyWrapper> tasks;
            tasks = (List<MyWrapper>)deserializer.Deserialize(textReader);
            textReader.Close();

            return tasks;
        }
    }
}

现在,当我尝试对其进行反序列化时,出现此错误

System.InvalidOperationException was unhandled
  Message="There is an error in XML document (2, 2)."
  Source="System.Xml"
  StackTrace:
       at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
       at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
       at ConsoleApplication1.Program.DeserializeFromXML() in C:\Users\chobo2\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs:line 55
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\chobo2\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs:line 34
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.InvalidOperationException
       Message="<Course xmlns=''> was not expected."
       Source="ap72r7cf"
       StackTrace:
            at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read5_ArrayOfMyWrapper()
       InnerException: 

我不确定为什么会这样。

一些附带问题 - 请在回答主要问题后回答

除非必须,否则我不想为这两个问题发布新的论坛帖子。

  1. 为什么给它一个对象类型很重要?就像为什么不将所有字段都设为字符串?

        [XmlElement("sharingKey")]
        public Guid SharingKey { get; set; }
    

是否只是为了在反序列化时获得在这种情况下的 Guid,以便以后不必将其从字符串转换为 Guid?

如果这是正确的,如果你从别人那里得到一个 xml 文件并且你想反序列化它,你怎么知道从中会产生什么对象呢?例如,你怎么知道我的“OutOf”实际上是一种可以为空的小数?事实上,C# 是如何知道这一点的?我没有看到任何可以暗示这是类型的东西。

  1. 当我让它真正反序列化时,我想知道如何制作我的 foreach 循环。因为我想浏览每个“MyWrapper”对象列表。但是在 MyWrapper 中有一个 Task 对象的集合。那么我是否必须在我的 foreach 循环中创建一个 for 循环才能获得它?或者,还有更好的方法?

谢谢

4

2 回答 2

1

好吧,我想问题是:您正在序列化一个MyWrapper,但试图反序列化一个List<MyWrapper>

那是行不通的——你将一个对象序列化到你的文件中,MyWrapper从那个文件反序列化时你会得到一个对象。

将反序列化更改为:

    static MyWrapper DeserializeFromXML()
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(MyWrapper));
        TextReader textReader = new StreamReader(@"C:\New folder\test.xml");
        MyWrapper tasks = (MyWrapper)deserializer.Deserialize(textReader);
        textReader.Close();
        return tasks;
    }

事情应该会再次起作用。

于 2010-01-24T21:10:52.500 回答
1

您正在尝试序列化 的单个实例MyWrapper,然后将其反序列化为它们的列表。如果您坚持一种方式或另一种方式(无论哪种方式),它都可以正常工作。例如:

static public void SerializeToXML(MyWrapper wrapper)
{
    XmlSerializer serializer = new XmlSerializer(typeof(List<MyWrapper>));
    using (TextWriter textWriter = File.CreateText("test.xml"))
    {
        // Create single-element list
        serializer.Serialize(textWriter, new List<MyWrapper>{wrapper});
    }
}

static List<MyWrapper> DeserializeFromXML()
{
    XmlSerializer deserializer = new XmlSerializer(typeof(List<MyWrapper>));
    using (TextReader textReader = File.OpenText("test.xml"))
    {
        return (List<MyWrapper>)deserializer.Deserialize(textReader);
    }
}

或(对于单个元素):

static public void SerializeToXML(MyWrapper wrapper)
{
    XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper));
    using (TextWriter textWriter = File.CreateText("test.xml"))
    {
        serializer.Serialize(textWriter, wrapper);
    }
}

static MyWrapper DeserializeFromXML()
{
    XmlSerializer deserializer = new XmlSerializer(typeof(MyWrapper));
    using (TextReader textReader = File.OpenText("test.xml"))
    {
        return (MyWrapper)deserializer.Deserialize(textReader);
    }
}

你只需要保持一致,仅此而已。

于 2010-01-24T21:13:51.887 回答