XML 序列化 "There is an error in XML document (2, 2)"的 C# 错误

标签 c# xml-serialization

全部,我正在尝试序列化和反序列化一个类,但反序列化失败了。有很多类似的线程,但我无法解决这个问题。我收到以下错误消息“XML 文档 (2, 2) 中存在错误”内部预期“{”不是预期的。”}”

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

namespace XMLSerialization
{
 [System.Xml.Serialization.XmlRootAttribute(Namespace = "",
     IsNullable = false)] 
 public class Level
 {
  private String _name;
  private String _background;

  public Level() 
  {
   _name = "LEVEL_NAME";
   _background = "LEVEL_BACKGROUND_IMAGE";
  }

  [XmlAttribute("LevelName")]
  public String LevelName
  {
   get { return _name; }
   set { _name = value; }
  }

  [XmlAttribute("Background")]
  public String Background
  {
   get { return _background; }
   set { _background = value; }
  }
 }
}

这是我用于反序列化的代码。序列化进行得很好,但反序列化没有进行。我认为我犯了一个微不足道的错误,但我无法解决这个问题!

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

namespace XMLSerialization
{
 class Program
 {
  static void Main(string[] args)
  {
   Level oLevel1 = new Level();

   XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
   ns.Add("", ""); 
   XmlSerializer serializer = new XmlSerializer(typeof(Level));
   TextWriter textWriter = new StreamWriter("Level1.xml");
   serializer.Serialize(textWriter, oLevel1, ns);
   textWriter.Close();

   Level oLevel2 = new Level();
   XmlSerializer deserializer = new XmlSerializer(typeof(List<Level>));
   TextReader textReader = new StreamReader("Level1.xml");
   oLevel2 = (Level)deserializer.Deserialize(textReader);
   textReader.Close();
  }
 }
}

最佳答案

我觉得你需要换行

XmlSerializer deserializer = new XmlSerializer(typeof(List<Level>));

XmlSerializer deserializer = new XmlSerializer(typeof(Level));

关于XML 序列化 "There is an error in XML document (2, 2)"的 C# 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5314585/

相关文章:

java - XStream 在 Android 上抛出异常 "no-args constructor"

C# WinUSB 无法在接口(interface)上调用 CloseHandle

c# - CIL 'fault' 子句与 C# 中的 'catch' 子句有何不同?

c# - ASP.NET 核心 2.1 XmlNodeReader

c# - MVC 5 反向代理身份验证并使用角色,仅使用用户名

java - 尝试更改空字符串的反序列化方式时发生 ConvertException : Element annotation required for field

c# - 是否可以保存当前的 XMLReader Position 供以后使用?

c# - 如何在 C# 中使用存储过程返回结果列表?

java - XML 序列化的简单框架 (Simple) 是否作为 SAX、Pull 或 DOM 解析器实现?

serialization - Linq to Xml VS XmlSerializer VS DataContractSerializer