为什么在 XML 反序列化函数中会出现此错误?
Why do I get this error at XML Deserialization function?
我创建了两个函数,XML 序列化和反序列化。
问题是我在反序列化时遇到错误。
您可以在下面找到这些功能:
public string Serialize(Object o)
{
using (var writer = new StringWriter())
{
new XmlSerializer(o.GetType()).Serialize(writer, o);
return writer.ToString();
}
}
public PathDetailsMessage Deserialize(string xml)
{
using (TextReader reader = new StringReader(xml))
{
XmlSerializer serializer = new XmlSerializer(typeof(PathDetailsMessage));
return (PathDetailsMessage)serializer.Deserialize(reader);
}
}
以及调用:
static void Main(string[] args)
{
PathDetailsBLL train = new PathDetailsBLL();
PathDetailsMessage pdm = train.GetDetails();
string xml = train.Serialize(pdm);
PathDetailsBLL dsa = new PathDetailsBLL();
PathDetailsMessage fds = new PathDetailsMessage();
fds = dsa.Deserialize(pdm.ToString());
Console.Write(fds);
Console.ReadKey();
}
在线return (PathDetailsMessage)serializer.Deserialize(reader);
我收到以下错误:
System.InvalidOperationException: 'There is an error in XML document (1, 1).'
XmlException: Data at the root level is invalid. Line 1, position 1.
你能帮帮我吗?
谢谢。
fds = dsa.Deserialize(pdm.ToString());
您想反序列化 xml 变量,但改用 pdm.ToString()。
尝试
fds = dsa.Deserialize(xml);
您似乎正在将 train.GetDetails()
返回的对象序列化为 XML 字符串,xml
,但您正在尝试反序列化该字符串(不一定是 XML 字符串)由 pdm.ToString()
返回。相反,您是否打算致电 dsa.Deserialize(xml)
?
我创建了两个函数,XML 序列化和反序列化。 问题是我在反序列化时遇到错误。 您可以在下面找到这些功能:
public string Serialize(Object o)
{
using (var writer = new StringWriter())
{
new XmlSerializer(o.GetType()).Serialize(writer, o);
return writer.ToString();
}
}
public PathDetailsMessage Deserialize(string xml)
{
using (TextReader reader = new StringReader(xml))
{
XmlSerializer serializer = new XmlSerializer(typeof(PathDetailsMessage));
return (PathDetailsMessage)serializer.Deserialize(reader);
}
}
以及调用:
static void Main(string[] args)
{
PathDetailsBLL train = new PathDetailsBLL();
PathDetailsMessage pdm = train.GetDetails();
string xml = train.Serialize(pdm);
PathDetailsBLL dsa = new PathDetailsBLL();
PathDetailsMessage fds = new PathDetailsMessage();
fds = dsa.Deserialize(pdm.ToString());
Console.Write(fds);
Console.ReadKey();
}
在线return (PathDetailsMessage)serializer.Deserialize(reader);
我收到以下错误:
System.InvalidOperationException: 'There is an error in XML document (1, 1).'
XmlException: Data at the root level is invalid. Line 1, position 1.
你能帮帮我吗?
谢谢。
fds = dsa.Deserialize(pdm.ToString());
您想反序列化 xml 变量,但改用 pdm.ToString()。 尝试
fds = dsa.Deserialize(xml);
您似乎正在将 train.GetDetails()
返回的对象序列化为 XML 字符串,xml
,但您正在尝试反序列化该字符串(不一定是 XML 字符串)由 pdm.ToString()
返回。相反,您是否打算致电 dsa.Deserialize(xml)
?