C# Serializacja + Deserializacja

0

Witam Wszystkich.
Podczas pisania aplikacji pojawił się problem z odczytem danych z XML'a.
Do pliku XML generuje dane dotyczące tabeli cenowej. są tam trzy wartość: Szerokość, Wysokość i Cena. Serializacja przebiega pomyślnie, plik XML jest zapisywany na dysku. Wszystko ok. Przy odczycie natomiast pojawiają się już problemy. Oto ostatni komunikat błędu:

 
{System.Xml.XmlException: Dane na poziomie głównym są nieprawidłowe. wiersz 1, pozycja 1.

Poniżej umieszczam kod funkcji zapisującej do XML'a i funkcji odczytującej.
Zapis:

 
XmlSerializer xml = new XmlSerializer(typeof(model.TablePrice));
                        FileStream stream = new FileStream(path, FileMode.Create);
                        //
                        for (int i = this.Construction.MinWidth / 100; i <= this.Construction.MaxWidth / 100; i++)
                        {
                            for (int j = this.Construction.MinHeight / 100; j <= this.Construction.MaxHeight / 100; j++)
                            {
                                model.TablePrice objTablePrice = new model.TablePrice() { 
                                    Width = (i * 100),
                                    Height = (j * 100),
                                    Price = 0,
                                };
                                xml.Serialize(stream, objTablePrice);
                            }
                        }
                        stream.Close();

i odczyt...

 
try
                    {
                        XmlSerializer xml = new XmlSerializer(typeof(model.TablePrice));
                        StringReader stream = new StringReader("Tables\\" + this.Construction.ID.ToString() + ".xml");
                        var dane = xml.Deserialize(stream);
                        stream.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.InnerException.ToString());
                        return;
                    }

Tak jak pisałem, błąd powstaje tylko przy próbie odczytu.

Bardzo proszę o pomoc.
Pozdrawiam,

0

Zawartość wygenerowanego pliku xml:

<?xml version="1.0"?>
<ArrayOfTablePrice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <TablePrice>
    <Width>900</Width>
    <Height>900</Height>
    <Price>0</Price>
  </TablePrice>
  <TablePrice>
    <Width>900</Width>
    <Height>1000</Height>
    <Price>0</Price>
  </TablePrice>
  <TablePrice>
    <Width>1000</Width>
    <Height>900</Height>
    <Price>0</Price>
  </TablePrice>
  <TablePrice>
    <Width>1000</Width>
    <Height>1000</Height>
    <Price>0</Price>
  </TablePrice>
</ArrayOfTablePrice>
 
0

Spróbuj deserializować:

List<model.TablePrice> 
2

Serializacja służy właśnie temu, żebyś nie musiał przechodzić pętlą przez całą swoją kolekcję. Potrzebujesz klasy która będzie owijką (Wrapper class) dla twojej listy klasTablePrice. W klasie ArrayOfTablePrices używasz atrybutu [XmlArrayAttribute] przez co twoje wartości są deserializowane do tablicy. Zawartość plików prices.xml i prices2.xml poniżej. W razie pytań pisz :).

 
using System;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace XmlSerializationSample
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");
			
			//your program logic
			ArrayOfTablePrices ArrayTablePrices = new ArrayOfTablePrices();
			ArrayTablePrices.TablePrices.Add(new TablePrice(){
			                                 	Width=100,
			                                 	Height=100,
			                                 	Price=3.5,
			                                 });
			ArrayTablePrices.TablePrices.Add(new TablePrice(){
			                                 	Width=200,
			                                 	Height=200,
			                                 	Price=6.5,
			                                 });
			//etc. at this point your list is fully populated eg. with a for loop
			
			//serialization
			XmlSerializer xmlSr = new XmlSerializer(typeof(ArrayOfTablePrices));
			StreamWriter fsWriter = new StreamWriter("prices.xml");
			xmlSr.Serialize(fsWriter, ArrayTablePrices);
                              
			//deserialization
			XmlSerializer xmlDeSr = new XmlSerializer(typeof(ArrayOfTablePrices));
			StreamReader fsReader = new StreamReader("prices2.xml");
			ArrayOfTablePrices newArrayTablePrices = new ArrayOfTablePrices(); //variable to store your deserialized values
			newArrayTablePrices = (ArrayOfTablePrices) xmlDeSr.Deserialize(fsReader);
			
			//checking if we got correct values
			foreach (TablePrice item in newArrayTablePrices.TablePrices)
			{
				Console.WriteLine("{0} width, {1} height, and the price is equal to {2}", item.Width, item.Height, item.Price);
			}
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
		
	}	

	
		public class TablePrice
		{
			[XmlElement]
			public int Width {get; set;}
			
			[XmlElement]
			public int Height {get; set;}
			
			[XmlElement]
			public double Price {get; set;}
		}
		
		[XmlRoot]
		public class ArrayOfTablePrices
		{
			[XmlArrayAttribute]
			public List<TablePrice> TablePrices {get; set;}
			
			public ArrayOfTablePrices()
			{
				this.TablePrices = new List<TablePrice>();
			}
		}
		
		
	
}
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTablePrices xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <TablePrices>
    <TablePrice>
      <Width>100</Width>
      <Height>100</Height>
      <Price>3.5</Price>
    </TablePrice>
    <TablePrice>
      <Width>200</Width>
      <Height>200</Height>
      <Price>6.5</Price>
    </TablePrice>
  </TablePrices>
</ArrayOfTablePrices> 
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTablePrices xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <TablePrices>
    <TablePrice>
      <Width>100</Width>
      <Height>100</Height>
      <Price>3.5</Price>
    </TablePrice>
    <TablePrice>
      <Width>200</Width>
      <Height>200</Height>
      <Price>6.5</Price>
    </TablePrice>
    <TablePrice>
      <Width>500</Width>
      <Height>200</Height>
      <Price>18</Price>
    </TablePrice>
    <TablePrice>
      <Width>200</Width>
      <Height>400</Height>
      <Price>10.5</Price>
    </TablePrice>
  </TablePrices>
</ArrayOfTablePrices> 

1 użytkowników online, w tym zalogowanych: 0, gości: 1