所有,我正在尝试序列化和反序列化类,并且反序列化失败。有大量类似的线程,但我无法解决这个问题。我收到以下错误“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();
}
}
}
答案 0 :(得分:8)
我认为您需要更改行
XmlSerializer deserializer = new XmlSerializer(typeof(List<Level>));
要
XmlSerializer deserializer = new XmlSerializer(typeof(Level));
答案 1 :(得分:3)
您序列化了Level
并正在尝试取消List<Level>
。