【问题标题】:Problem with Serialize/Deserialize objects to/from XML file序列化/反序列化对象到 XML 文件的问题
【发布时间】:2011-05-08 19:50:45
【问题描述】:

我必须先将 xml 文件反序列化为 List,然后放大此列表并通过添加 1 个对象来序列化所有文件(为此需要放大)

来自 XML 的代码:

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
           <name>Danie</name>
           <lastName>McJackie</lastName>
           <age>27</age>
 </Person>

.cs 文件中的代码:我注释了出错的地方并复制了错误消息

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

public partial class _Default : System.Web.UI.Page 
{
   protected void Page_Load(object sender, EventArgs e)
   {

   }
   private List<Person> Deserialize(string path)
   {
       using (FileStream fs = new FileStream(path, FileMode.Open))
       {
           XmlSerializer ser = new XmlSerializer(typeof(List<Person>));
           return (List<Person>)ser.Deserialize(fs);
           //There is an error in XML document (2, 2).
           // I got this error and don't know how to manage with it.
       }
   }

   protected void Button1_Click(object sender, EventArgs e)
   {
       string path = Server.MapPath(Request.ApplicationPath + "/test.xml");
       List<Person> people = File.Exists(path) ? Deserialize(path) :new List<Person>();
       people.Add(new Person(TextBox1.Text, TextBox2.Text, int.Parse(TextBox3.Text)));
       using (FileStream fs = File.OpenWrite(path))
       {
           XmlSerializer ser = new XmlSerializer(typeof(List<Person>));
           ser.Serialize(fs, people);
       }


   }
}

至少要序列化的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;



[Serializable]
public class Person
{

   public string name;
   public string lastName;
   public int age;
   public Person(string _name, string _lastName, int _age)
   {
       name = _name;
       lastName = _lastName;
       age = _age;
   }
   public Person()
   {

   }
}

异常详情:

System.InvalidOperationException was unhandled by user code
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(Stream stream)
   at _Default.Deserialize(String path) in e:\Programy c#\WebSites\ASP8\Default.aspx.cs:line 22
   at _Default.Button1_Click(Object sender, EventArgs e) in e:\Programy c#\WebSites\ASP8\Default.aspx.cs:line 29
   at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)                
       at System.Web.UI.Page.ProcessRequestMain(Boolean                                                                includeStagesBeforeAsyncPoint,       Boolean includeStagesAfterAsyncPoint)
  InnerException: System.InvalidOperationException
       Message=<Person xmlns=''> was not expected.
   Source=_1r-cm1p
   StackTrace:
        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read3_ArrayOfPerson()
   InnerException: 

这是我上次编辑时添加的内容

反序列化文件.cs:

string path = Server.MapPath(Request.ApplicationPath + "/test.xml");
    using (FileStream fs = new FileStream(path, FileMode.Open))
    {
        XmlSerializer ser = new XmlSerializer(typeof(List<Person>));
        List<Person> os = (List<Person>)ser.Deserialize(fs);
        foreach (var i in os)
        {
            Label1.Text += i.Name + "<hr />" + i.LastName + "<hr />" + i.Age.ToString() + "<hr />";
        }

        fs.Close();

一切正常,感谢大家的帮助:)

【问题讨论】:

  • 错误是什么?异常详情?
  • 只是一个助手 - 稍微改变你的命名约定 _name 应该是你的私有成员,你的公共字符串名称应该是公共字符串名称(注意大写)
  • 2,2 处的错误几乎总是意味着文件开头的回车 - 是这种情况吗?

标签: c# asp.net xml-serialization


【解决方案1】:

代替

XmlSerializer ser = new XmlSerializer(typeof(List<Person>));

试试

XmlSerializer ser = new XmlSerializer(typeof(Person));

【讨论】:

  • 当我更改时出现错误:无法将“Person”类型的对象转换为“System.Collections.Generic.List`1[Person]”。
  • 但它现在可以工作了。只需调整您的代码,因为它返回一个人。
  • 抱歉,我看到你正在序列化 Person 列表,所以你的 XML 应该不止一个人,对吧?
  • 那么有问题了,因为你的 XML 是 Person 类型,应该是 ArrayOfPerson 类型
  • 您拥有的 person 类型的 XML 错误。把它扔掉,只用 List 重新开始
【解决方案2】:

你的命名空间说明符中有行尾吗?

   <?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://
www.w3.org/2001/XMLSchema">

应该是

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

从问题中复制时,行尾似乎在那里

【讨论】:

  • 你是什么意思?对不起,我不明白
  • 我希望您确实看到两个 sn-ps 的区别?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
相关资源
最近更新 更多