Многократное корневое декларирование в XML-файле во время сериализации - PullRequest
1 голос
/ 12 сентября 2011

Я делаю сериализацию Xml, но застрял в одной ошибке, которая у меня есть почти одну неделю, у меня есть простая веб-страница, такая как

FirstNameTextBox: LastNameTextBox: EmailTextBox:

SubmitButton

у меня есть два класса, называемые Customer и Customer List, класс Customer выглядит следующим образом

namespace XmlSearlizeProject.Classes
{
    [Serializable]
    [XmlRoot("CustomerData")]
    public class Customer
    {
        string id = default(string);
        string firstName = default(string);
        string lastName = default(string);
        string email = default(string);
        public Customer()
        {

        }
        public Customer(string id, string firstName, string lastName, string email)
        {
            CustomerId = id;
            FirstName = firstName;
            LastName = lastName;
            Email = email;

        }
        [XmlElement("CustomerId")]
        public string CustomerId
        {
            get
            {
                return this.id;
            }
            set
            {
                this.id = value;
            }
        }
        [XmlElement("FirstName")]
        public string FirstName
        {
            get
            {
                return this.firstName;
            }
            set
            {
                this.firstName = value;
            }
        }
         [XmlElement("LastName")]
        public string LastName
        {
            get
            {
                return this.lastName;
            }
            set
            {
                this.lastName = value;
            }
        }
         [XmlElement("CustomerEmail")]
        public string Email
        {
            get
            {
                return this.email;
            }
            set
            {
                this.email = value;
            }
        }
    }
}

, а класс CustomerList выглядит следующим образом

namespace XmlSearlizeProject.Classes
{
    [Serializable]
    public class CustomerList:List<Customer>
    {
    }
}

, а код, выполняющий сериализацию XML:

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

        }

        private void GeneralFunction(Stream xmlStream)
        {
            string customerId = Guid.NewGuid().ToString();
            Classes.CustomerList customerList = new Classes.CustomerList{ 
    new Classes.Customer
    {
        FirstName = this.FirstNameTextBox.Text,
        LastName = this.LastNameTextBox.Text,
        Email = this.EmailTextBox.Text,
        CustomerId = customerId
    }
};


            Classes.Customer customer = new Classes.Customer();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Classes.CustomerList));
            XmlDocument document = new XmlDocument();
            document.Load(xmlStream);

            XmlElement id = document.CreateElement("Id");
            id.InnerText = customerId;
            document.DocumentElement.InsertAfter(id, document.DocumentElement.LastChild);

            XmlElement firstName = document.CreateElement("FirstName");
            firstName.InnerText = customer.FirstName;
            document.DocumentElement.InsertAfter(firstName, document.DocumentElement.LastChild);

            XmlElement lastName = document.CreateElement("LastName");
            lastName.InnerText = customer.LastName;
            document.DocumentElement.InsertAfter(lastName, document.DocumentElement.LastChild);

            XmlElement email = document.CreateElement("Email");
            email.InnerText = customer.Email;
            document.DocumentElement.InsertAfter(email, document.DocumentElement.LastChild);
            XmlTextWriter xmlTextWriter = new XmlTextWriter(xmlStream, Encoding.UTF8);
            xmlSerializer.Serialize(xmlTextWriter, customerList);
            xmlStream.Close();
        }

        private void SerializeCustomer()
        {

                Stream xmlWriterStream = new FileStream(Server.MapPath("~/Customer.xml"), FileMode.OpenOrCreate, FileAccess.ReadWrite);
                GeneralFunction(xmlWriterStream);
                xmlWriterStream.Close();
        }


        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            SerializeCustomer();
        }
    }
}

и теперь моя проблема заключается в том, что, когда я добавляю первого клиента с помощью функции сериализации, мой XML-файл выглядит следующим образом

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCustomer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Customer>
    <CustomerId>34f15068-4331-4253-8660-d1ce2199ed6d</CustomerId>
    <FirstName>haseeb</FirstName>
    <LastName>khan</LastName>
    <CustomerEmail>abc@hotmtail.com</CustomerEmail>
  </Customer>
</ArrayOfCustomer>

Но когда я пытаюсь добавить другого клиента, используя тот жеФункция сериализации с той же веб-страницей, что и мой XML-файл, выглядит следующим образом

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCustomer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Customer>
    <CustomerId>34f15068-4331-4253-8660-d1ce2199ed6d</CustomerId>
    <FirstName>haseeb</FirstName>
    <LastName>khan</LastName>
    <CustomerEmail>abc@hotmtail.com</CustomerEmail>
  </Customer>
</ArrayOfCustomer><?xml version="1.0" encoding="utf-8"?>
<ArrayOfCustomer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Customer>
    <CustomerId>924e5fe3-d5ce-41c2-a850-4d3da1e44f91</CustomerId>
    <FirstName>ammar</FirstName>
    <LastName>khan</LastName>
    <CustomerEmail>xyz@hotmail.com</CustomerEmail>
  </Customer>
</ArrayOfCustomer>

Я не понимаю, как исправить эту ошибку, мне нужен мой XML-файл, например, когда я добавляю нового клиента

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCustomer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Customer>
    <CustomerId>34f15068-4331-4253-8660-d1ce2199ed6d</CustomerId>
    <FirstName>haseeb</FirstName>
    <LastName>khan</LastName>
    <CustomerEmail>abc@hotmtail.com</CustomerEmail>
  </Customer>
  <Customer>
    <CustomerId>924e5fe3-d5ce-41c2-a850-4d3da1e44f91</CustomerId>
    <FirstName>ammar</FirstName>
    <LastName>khan</LastName>
    <CustomerEmail>xyz@hotmail.com</CustomerEmail>
  </Customer>
</ArrayOfCustomer>

, пожалуйста, помогите, у меня есть эта проблема в течение одной недели, и я попробовал все, но смог решить эту ошибку, если кто-нибудь поможет мне, я буду тему благодарен

...