Les Snippets

Connexion

Serialisation et deserialisation d'un objet vers du xml

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 17/03/2006 19:51:25 et initié par jesusonline [Liste]
Date de mise à jour : 08/04/2006 14:06:45
Vue : 29400
Catégorie(s) : Trucs & Astuces, XML
Langages dispo pour ce code :
- VB 2005, VB.NET 1.x
- C# 1.x, C# 2.x
- Java
- PHP 5
- C# 2.x



Langage : VB.NET 1.x , VB 2005
Date ajout : 17/03/2006
Posté par JesusOnline [Liste]

Imports System.Xml

Imports System.Xml.Serialization

Imports System.Text
Imports System.IO



Public Class Utilities 
    
     Public Shared Function Serialize(ByVal Obj As Object) As String
          Dim serializer As New XmlSerializer(Obj.GetType) 
          Dim sb As New StringBuilder()
          Dim writer As New StringWriter(sb) 
          serializer.Serialize(writer, Obj)
          writer.Close()
          writer.Dispose() 

          Return sb.ToString() 
      End Function


      Public Shared Function Deserialize(ByVal str As String, ByVal t As Type) As Object
          Dim serializer As New XmlSerializer(t) 
          Dim reader As New StringReader(str)
          Dim obj As Object = serializer.Deserialize(reader) 
          reader.close()
          reader.Dispose()

          Return obj 
      End Function


End Class




Langage : C# 1.x , C# 2.x
Date ajout : 17/03/2006
Posté par JesusOnline [Liste]
DateMAJ : 08/04/2006

using System.Xml;

using System.Xml.Serialization;

using System.Text;

using System.IO;

public class Utilities
{

     public static String Serialize(Object Obj) 
     {

          XmlSerializer serializer = new XmlSerializer(Obj.GetType()); 
          StringBuilder sb = new StringBuilder();
          StringWriter writer = new StringWriter(sb); 
          serializer.Serialize(writer, Obj);
          writer.Close();
          writer.Dispose();
          return sb.ToString(); 
     }



     public static Object Deserialize(String str, Type t) 
     {
          XmlSerializer serializer = new XmlSerializer(t); 
          StringReader reader = new StringReader(str);

          Object obj = serializer.Deserialize(reader); 
          reader.Close();
          reader.Dispose();
          return obj; 
      }

}


Langage : Java
Date ajout : 20/03/2006
Posté par neodante [Liste]

import java.beans.*; import java.io.*; public class XMLSerialisationSample {         public static void main(String[] args) {                 // Création des noeuds         System.out.println("Affichage avant sérialisation :");         Node root = new Node("Racine");    // Noued racine         Node node1 = new Node("Noeud 1"); // D'autres noeuds         Node node2 = new Node("Noeud 2");                 // Construction de la liste chainée         root.attach(node1);         node1.attach(node2);                 // Affichage de notre liste         root.printList();                 // Enregistrement de nos noeuds à partir de la racine         try {             XMLEncoder e = new XMLEncoder(                     new BufferedOutputStream(                     new FileOutputStream("TestNode.xml")));             e.writeObject(root);             e.close();         } catch (FileNotFoundException e1) {             e1.printStackTrace();         }                 // Destruction de notre liste         node2 = null;         node1 = null;         root = null;                 // Lecture (désérialisation) de notre fichier XML         try {             XMLDecoder d = new XMLDecoder(new BufferedInputStream(                     new FileInputStream("TestNode.xml")));             root = (Node) d.readObject();             d.close();         } catch (FileNotFoundException e) {             e.printStackTrace();         }                 // Affichage de notre liste         System.out.println("Affichage après désérialisation :");         root.printList();     } }

... Classe dans son propre fichier 

public class Node implements Serializable {     private Object value;     private Node prev;     private Node next;     public Node() {         prev = null;         next = null;         value = null;     }         public Node(Object val){         value = val;     }         public Node getNext() {         return next;     }     public void setNext(Node next) {         this.next = next;     }     public Node getPrev() {         return prev;     }     public void setPrev(Node prev) {         this.prev = prev;     }     public Object getValue() {         return value;     }     public void setValue(Object value) {         this.value = value;     }         public void attach(Node node){         next = node;         node.prev = this;     }         public boolean isFirst(){         return prev == null;     }         public void printList(){         Node n = this;         while (n != null){             System.out.print(n + "\n");             n = n.next;         }     }         public String toString() {         return "<Node> value = " + (value != null ? value : "NULL");     } }

Remarque :
Cet exemple est très simple, tout comme l'est la sérialisation XML. Pour de plus amples informations sur ce principe, veuillez consulter la javadoc :

- http://java.sun.com/j2se/1.4.2/docs/api/java/beans/XMLEncoder.html
- http://java.sun.com/j2se/1.4.2/docs/api/java/beans/XMLDecoder.html

- http://java.sun.com/j2se/1.4.2/docs/guide/serialization/


Attention : la sérialisation XML est spécialisé dans les javaBeans
(c'est à dire les classes possédant des propriétés (un attributs et des accesseurs get/set appropriés) publiques.


Il y a 4 choses qui sont donc INDISPENSABLE pour ça :
- Un constructeur par défaut (sans paramètres)
- La classe doit implémenter l'interface Serializable
- Toutes les propriétés que vous devez enregistrer doivent avoir des accesseurs (get/set)
- Etre une classe PUBLIQUE !! public class (La classe doit être dans son propre fichier !)
Langage : PHP 5
Date ajout : 22/03/2006
Posté par malalam [Liste]
DateMAJ : 27/03/2006

<?php
/**
* CLASS xmlSerializer
* object to xml serialization and unserialization
* @auteur : johan <barbier_johan@hotmail.com>
* @version : 1
* @date : 2006/03/22
*
* free to use, modify, please just tell me if you make any changes :-)
*/
class xmlserialize {

 /**
 * private object oObj
 * the object we work on
 */
 private $oObj = null;
 /**
 * private array of object oPropObj
 * objects needed by the main object, because some of its properties are objects
 */
 private $oPropObj = array ();
 /**
 * private array aProps
 * the PUBLIC properties of the object
 */
 private $aProps = array ();
 /**
 * private string xml
 * the xml serailization of the object
 */
 private $xml = '';
 /**
 * public string node
 * a fragment of the xml string
 */
 public $node = '';

 /**
 * public function __construct
 * constructor
 * @Param (object) $obj : the object we want to serialize/unserialize
 * @Param (array) $oPropObj : array of objects needed by the main object
 */
 public function __construct ($obj, array $oPropObj = array ()) {
  if (!is_object ($obj)) {
   return false;
  } else {
   $this -> oObj = $obj;
  }
  if (!empty ($oPropObj)) {
   foreach ($oPropObj as $clef => $oVal) {
       if (is_object ($oVal)) {
      $this -> oPropObj[$clef]['object'] = $oVal;
      $this -> oPropObj[$clef]['class'] = get_class ($oVal);
    }
   }
  }
 }

 /**
 * public function getProps ()
 * method used to get the public properties of the object
 */
 public function getProps () {
  $this -> aProps = get_object_vars ($this -> oObj);
 }

 /**
 * private function recVarsToXml
 * method used to serialize the object, recursive
 * @Params (DomDocument) & docXml : the DomDocument object
 * @Params (DomElement) & xml : the current DomElement object
 * @Params (array) & aProps : the array of properties we work on recursively
 */
 private function recVarsToXml (& $docXml, & $xml, & $aProps) {
  foreach ($aProps as $clef => $val) {
   if (empty ($clef) || is_numeric ($clef)) {
    $clef = '_'.$clef;
   }
   $domClef = $docXml -> createElement ((string)$clef);
   $domClef = $xml -> appendChild ($domClef);
   if (is_scalar ($val)) {
    $valClef = $docXml -> createTextNode ((string)$val);
    $valClef = $domClef -> appendChild ($valClef);
   } else {
    if (is_array ($val)) {
     $this -> recVarsToXml ($docXml, $domClef, $val);
    }
    if (is_object ($val)) {
     $oXmlSerialize = new self ($val);
     $oXmlSerialize -> getProps ();
     $oXmlSerialize -> varsToXml ();
     $objClef = $docXml -> importNode ($oXmlSerialize -> node, true);
     $objClef = $domClef -> appendChild ($objClef);
    }
   }
  }
 }

 /**
 * public function varsToXml
 * method used to serialize the object
 * @Return (string) $xml : the xml string of the serialized object
 */
 public function varsToXml () {
  $docXml = new DOMDocument ('1.0', 'iso-8859-1');
  $xml = $docXml -> createElement ('object_'.get_class ($this -> oObj));
  $xml = $docXml -> appendChild ($xml);
  $this -> recVarsToXml ($docXml, $xml, $this -> aProps);
  $this -> node = $xml;
  return $this -> xml = $docXml -> saveXML ();
 }

 /**
 * private function recXmlToVars
 * method used to unserialize the object, recursive
 * @Param (array) aProps : the array we work on recursively
 */
 private function recXmlToVars ($aProps) {
  foreach ($aProps as $clef => $val) {
   $cpt = count ($val);
   if ($cpt > 0) {
    foreach ($val as $k => $v) {
     $cpt2 = count ($v);
     if ($cpt2 > 0) {
        if (substr ($k, 0, 7) === 'object_') {
          foreach ($this -> oPropObj as $kObj => $vObj) {
              if ($this -> oPropObj[$kObj]['class'] === substr ($k, 7)) {
                                    $oXmlSerializer = new self ($this -> oPropObj[$kObj]['object']);
                                    $oXmlSerializer -> getProps ();
                                    $sXml = $oXmlSerializer -> varsToXml ();
                                    $oXmlSerializer -> xmlToVars ($sXml);
                                    $this -> oObj -> {$clef}[substr ($k, 7)] = $oXmlSerializer -> getObj ();
                                }
       }
      } else {
       $this -> recXmlToVars ($v);
      }
     } else {
      if ($k{0} === '_') {
       $k = substr ($k, 1, strlen($k) - 1);
      }
      $this -> oObj -> {$clef}[$k] = current ($v);
     }
    }
   } elseif (!empty ($val)) {
    $this -> oObj -> $clef = current ($val);
   }
  }
 }

 /**
 * public function xmlToVars
 * method used to unserialize the object
 * @Param (string) xml : optional xml string (an already serialized object)
 */
 public function xmlToVars ($xml = '') {
  if (empty ($xml)) {
   $xml = simplexml_load_string ($this -> xml);
  } else {
   $xml = simplexml_load_string ($xml);
  }
  $this -> recXmlToVars ($xml);
 }

 /**
 * public function getObj
 * method used to get the unserialized object
 * @Return (object) oObj : the unserialized object
 */
 public function getObj () {
  return $this -> oObj;
 }

}
?>

Remarque :
Seules les propriétés PUBLIQUES de l'objet seront linéarisées/délinéarisées (je n'ai pas encore trouvé de moyen d'accéder ainsi aux propriétés protégées ou privées)
Langage : C# 2.x
Date ajout : 24/03/2006
Posté par iso8859 [Liste]

using System;

using System.Xml.Serialization;

using System.IO;
namespace Utilities 
{
  /// <summary>

  /// Serialisation / Deserialisation avec les generics .NET 2.0

  /// Sauvegare / chargement vers fichier, string ou stream

  /// </summary>
    public class XMLSerialize<T> : MarshalByRefObject where T : new() 
    {
      // Le serialiser est statique ainsi il n'est construit qu'une fois par le CLR

      // gain de temps enorme qui evite de faire une reflection à chaque utilisation
      static XmlSerializer m_serializer = new XmlSerializer(typeof(T));
      static public T LoadFromFile(string fileName) 
      {
        T result;
        try

        {
          using (FileStream input = new FileStream(fileName, FileMode.Open)) 
          {
            result = (T)m_serializer.Deserialize(input);
          }
        }
        catch

        {
          result = new T(); 
        }
        return result; 
      }
      static public T LoadFromString(string data) 
      {
        T result;

        try

        {
          using (StringReader sr = new StringReader(data)) 
          {
            result = (T)m_serializer.Deserialize(sr);
          }
        }
        catch

        {
          result = new T(); 
        }
        return result; 
      }
      static public T LoadFromStream(Stream stream) 
      {
        T result;

        try

        {
          XmlSerializer read = new XmlSerializer(typeof(T)); 
          result = (T)m_serializer.Deserialize(stream);
        }
        catch

        {
          result = new T(); 
        }
        return result; 
      }
      public void SaveToStream(Stream stream) 
      {
        m_serializer.Serialize(stream, this); 
      }
      public string SaveToString() 
      {
        StringWriter sw = new StringWriter(); 
        m_serializer.Serialize(sw, this);
        return sw.ToString(); 
      }
      public void SaveToFile(string fileName) 
      {
        using (StreamWriter sm = new StreamWriter(fileName)) 
        {
          m_serializer.Serialize(sm, this); 
        }
      }
    }

    // Exemple d'utilisation
    public class Exemple : XMLSerialize<Exemple> 
    {
      public string m_nom; public int m_age; 
    }

    public class M

    {
      public static void Main() 
      {
        Exemple e = new Exemple(); e.m_nom = "Newton"; 
        e.m_age = 45;

        string sauve = e.SaveToString(); // Sauver vers une chaîne

        Exemple e2 = Exemple.LoadFromString(sauve); // Création d'une nouvelle instance

      }
    }
  }


Snippets en rapport avec : Serialisation, Deserialisation, Xml, Serialize, Deserialize



Codes sources en rapport avec : Serialisation, Deserialisation, Xml, Serialize, Deserialize

{Visual Basic, VB6, VB.NET, VB 2005} [LAMEGRID] SÉRIALISATION - DÉSERIALISATION
Classe permettant la sérialisation - désérialisation d'une LameGrid. Accompagnée d'un exemple d'util...

{PDA / PocketPC} POCKETAPPCONFIG : CONSERVER SES PRÉFÉRENCES
Dans de nombreux cas il est inutile d'utiliser une base de donnée pour sauvegarder quelques préféren...

{C# / C#.NET} DESSINER EN XML
C'est le prolongement d'un test d'embauche : On m'a demandé de faire un composant (dll) qui serait c...

{JAVA / J2EE} MANIPULATION DE FICHIER XML
le code creé un fichier XML depuis une base de données Mysql ensuite il auras l'affichage du conten...

{PHP} [PHP5] XML OBJECT SERIALIZER/UNSERIALIZER
Bon...je vais tenter d'expliquer le concept ;-) Les adeptes de la POO PHP connaisse les fonctions s...

{C# / C#.NET} [C#] [XML] SERIALIZATION STRING, COLOR, ARRAYLIST, HASHTABLE, DATETIME
Voici un ensemble de classes qui vont permettre en englobant des classes de bases de C# de faire de ...

{JAVA / J2EE} SÉRIALISATION
c un petit programme qui vous presente d'une maniere tres simple la facon d'utiliser une des methode...

{Flash} XMLIZER : OBJET FONCTIONNANT SUR LE PRINCIPE DE "SERIALIZE()" ET "UNSERIALIZE()" DE PHP.
Après mettre pencher sur le "serialize()" et "unserialize()" de PHP grace a Skreo, je me suis vite r...

{Flash} CLASSE SERIALIZER : SERIALIZE() ET UNSERIALIZE() IDENTIQUES À PHP
La classe Serializer contient 2 fonction publiques : serialize() et unserialize() identiques à php ...

{C# / C#.NET} SÉRIALISEZ VOS FICHIERS DE CONFIGURATION !!!
Combien de fois avez-vous réécris vos méthodes permettant de gérer vos fichiers de configurations ??...