簡體   English   中英

在XML文件中對對象進行序列化/反序列化的問題

[英]Problem with Serialize/Deserialize objects to/from XML file

我必須首先將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();

一切正常,謝謝大家的幫助:)

代替

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

嘗試

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

您的命名空間說明符中是否有行尾?

   <?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">

從問題中復制時,行尾似乎在那里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM