开发者

XML Serialization

开发者 https://www.devze.com 2023-04-03 02:32 出处:网络
I want to add multiple record one by one using XML serialization. I have three text boxes and a button which is used to get the data from the user and then serializae in XML file. However, when I add

I want to add multiple record one by one using XML serialization. I have three text boxes and a button which is used to get the data from the user and then serializae in XML file. However, when I add one record on it's own it's fine, but for the another record it declares multiple root elements which I am not able to handle.

I am doing XML serialization and I am getting this error in XML File

**<?xml version="1.0" encoding="utf-8"?>
<sroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:my-examples:shaping">**
  <CustomerId>3a8bb49e-f616-49a5-8ec8-1886881c3042</CustomerId>
  <FirstName>HASEEB</FirstName>
  <LastName>KHAN</LastName>
  <CustomerEmail>SDCFDS</CustomerEmail>
**</sroot><?xml version="1.0" encoding="utf-8"?>
<sroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:my-examples:shaping">**
  <CustomerId>6d2cbe5e-e1fb-4526-9f98-bf396b4ded55</CustomerId>
  <FirstName>ammae</FirstName>
  <LastName>wdfjk</LastName>
  <CustomerEmail>sdkcbnk</CustomerEmail>
</sroot>

As you can see in above XML code that there are multiple root element is written and I am not able to fix that I have a class called customer.cs and the code is written in this class is

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

namespace XmlSearlizeProject.Classes
{
    [Serializable]
    [XmlRoot(ElementName = "sroot", Namespace = "urn:my-examples:shaping")]
    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
            开发者_JAVA百科{
                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;
            }
        }
    }
}

And my C# code is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;
namespace XmlSearlizeProject.WebPages
{
    public partial class CustomerPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        private void GeneralFunction(Stream xmlStream)
        {
            //xmlStream.Close();
            string customerId = Guid.NewGuid().ToString();
            Classes.Customer customer = new Classes.Customer(customerId,this.FirstNameTextBox.Text,this.LastNameTextBox.Text,this.EmailTextBox.Text);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Classes.Customer));
            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("rtgr");
            firstName.InnerText = customer.FirstName;
            document.DocumentElement.InsertAfter(firstName, document.DocumentElement.LastChild);

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

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

            xmlStream.Close();
        }

        private void SerializeCustomer()
        {
            if (File.Exists(Server.MapPath("~/Customer.xml")))
            {
                Stream xmlWriterStream = new FileStream(Server.MapPath("~/Customer.xml"), FileMode.Open, FileAccess.ReadWrite);
                GeneralFunction(xmlWriterStream);
                xmlWriterStream.Close();
            }
        }

        private void DeSerializeCustomer()
        {
            Stream xmlReaderStream = new FileStream(Server.MapPath("~/Customer.xml"), FileMode.Open, FileAccess.Read, FileShare.Read);
            XmlSerializer xmlDeSerializer = new XmlSerializer(typeof(Classes.Customer));
            Classes.Customer customer = (Classes.Customer)xmlDeSerializer.Deserialize(xmlReaderStream);
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            //if (!File.Exists(Server.MapPath("~/Customer.xml")))
            //{
                SerializeCustomer();
            //}
            //else
            //{
            //    DeSerializeCustomer();
            //}
        }
    }
}


It looks like you're serializing one customer at a time, versus serializing a list/array/collection of customers to the XML file.

Serializing one works because you have 1 root element - Customer. However, when serializing many, you will need to serializing the collection of customers to the XML file.

So then you'll have (example purposes only):

<Customers>
 <sroot/>
 <sroot/>
</Customers>

A few articles to look at on this:

C# Serializing a Collection of Objects

http://wcode.net/2009/08/serialize-collection-of-object-in-c/

http://www.codeproject.com/KB/cs/objserial.aspx


Define a schema definition (xsd) in the format you want your xml to look like. Then you can use some external tools like xsd2code. This would Auto-generate your "Customer" class to the format of your xsd. (In case if you are doing in manually). Then your xml will match the way you define in your xsd. Give it a try, defining a xsd for your xml is always a better practice.


You could just inherit from list something like this...

[Serializable]
[XmlRoot(ElementName = "sroot", Namespace = "urn:my-examples:shaping")]
public class CustomerList : List<Customer>
{
}

[Serializable]
public class Customer
{
    ...
}

Example usage...

CustomerList customerList = new CustomerList 
{ 
    new Customer
    {
        FirstName = "John",
        LastName = "Doe",
        Email = "johndoe@foobar.com",
        CustomerId = "123"
    },
    new Customer
    {
        FirstName = "Jane",
        LastName = "Doe",
        Email = "janedoe@foobar.com",
        CustomerId = "456"
    }
};

Then your method would serialize the list (instance of CustomerList)...

SerializeCustomerList(CustomerList customers)
{
    // Do serialize CustomerList instance...
}

Then the resulting XML would look like...

<sroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:my-examples:shaping">
  <Customer>
    <CustomerId>123</CustomerId>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <CustomerEmail>johndoe@foobar.com</CustomerEmail>
  </Customer>
  <Customer>
    <CustomerId>456</CustomerId>
    <FirstName>Jane</FirstName>
    <LastName>Doe</LastName>
    <CustomerEmail>janedoe@foobar.com</CustomerEmail>
  </Customer>
</sroot>

Hope it helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消