Serializar um Hashtable para xml

<< Click to Display Table of Contents >>

Navigation:  XML >

Serializar um Hashtable para xml

Previous pageReturn to chapter overviewNext page

 

Salvar Hashtable

 

Hashtable ht = new Hashtable();

 

ht.Add("Nome", "Junior");

ht.Add("Telefone", "Samsung");

ht.Add("Cidade", "Floripa");

 

using (StreamWriter writer = new StreamWriter("d:\a.xml"))

{

   writer.Write(Serializador.Serializar(ht));

}

 

Carregar Hashtable

 

StreamReader reader = new StreamReader("d:\a.xml");

StringBuilder sb = new StringBuilder();

while (!reader.EndOfStream)

{

   sb.Append(reader.ReadLine());

}

reader.Close();

 

Hashtable ht = Serializador.Deserializar(sb.ToString());

 

// listando conteúdo!

IDictionaryEnumerator en = ht.GetEnumerator();

while (en.MoveNext())

{

       ...     en.Key

       ...     en.Value

}

 

Serializador.cs

 

using System;

using System.IO;

using System.Xml.Serialization;

using System.Collections;

using System.Collections.Generic;

 

// classe necessária para serializar um hashtable

public class DataItem

{

  public string Key;

  public string Value;

 

  public DataItem()

   {

   }

 

  public DataItem(string key, string value)

   {

       Key = key;

       Value = value;

   }

}

 

class Serializador

{

  public static string Serializar(Hashtable ht)

   {

      // cria list de objeto DataItem para armazenar os valores

      List<DataItem> tempdataitems = new List<DataItem>(ht.Count);

 

      // transfere os valores de uma lista pra outra

      foreach (string key in ht.Keys)

       {

           tempdataitems.Add(new DataItem(key, ht[key].ToString()));

       }

 

      // cria um serializador com o tipo DataItem

      XmlSerializer serializer = new XmlSerializer(typeof(List<DataItem>));

      StringWriter sw = new StringWriter();

      XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

       ns.Add("", "");

       serializer.Serialize(sw, tempdataitems, ns);

 

      return sw.ToString();

   }

 

  public static Hashtable Deserializar(string xml)

   {

      Hashtable ht = new Hashtable();

 

      XmlSerializer xs = new XmlSerializer(typeof(List<DataItem>));

      StringReader sr = new StringReader(xml);

 

      List<DataItem> templist = (List<DataItem>)xs.Deserialize(sr);

 

      foreach (DataItem di in templist)

       {

           ht.Add(di.Key, di.Value);

       }

 

      return ht;

   }

}