views:

63

answers:

2

I have an xml document that was serialized into a byte stream and persisted to a database. I any get the byte stream back, but how do I convert it into an xml file again?

A: 

It really depends on how the XML is serialize to a byte stream, etc., but you probably want to take a look at the SAXParser class, especially the [parse() methods][2].

[2]: http://java.sun.com/javase/6/docs/api/javax/xml/parsers/SAXParser.html#parse(java.io.InputStream, org.xml.sax.helpers.DefaultHandler)

ig0774
A: 

Here are a couple of methods to convert back and forth to byte[] and back. Of course the Object can be a String

   public static Object byteArrayToObject(byte[] data)
   {
      Object retObject = null;
      if (data != null)
      {
         ByteArrayInputStream bis = null;
         ObjectInputStream ois = null;
         try
         {
            bis = new ByteArrayInputStream(data);
            ois = new ObjectInputStream(bis);

            retObject = ois.readObject();
         }
         catch(StreamCorruptedException e)
         {
            e.printStackTrace(System.out);
         }
         catch(OptionalDataException e)
         {
            e.printStackTrace(System.out);
         }
         catch(IOException e)
         {
            e.printStackTrace(System.out);
         }
         catch(ClassNotFoundException e)
         {
            e.printStackTrace(System.out);
         }
         finally
         {
            try
            {
               bis.close();
            }
            catch(IOException ex)
            {
               ex.printStackTrace(System.out);
            }

            try
            {
               ois.close();
            }
            catch(IOException ex)
            {
               ex.printStackTrace(System.out);
            }
         }
      }
      return retObject;
   }

   public static byte[] objectToByteArray(Object anObject)
   {
      byte[] results = null;
      if (anObject != null)
      {
         // create a byte stream to hold the encoded object
         ByteArrayOutputStream bytes = new ByteArrayOutputStream();

         try
         {
            // create a stream to write the object
            ObjectOutputStream ostrm = new ObjectOutputStream(bytes);

            // write the object
            ostrm.writeObject(anObject);

            // ensure that the entire object is written
            ostrm.flush();

            results = bytes.toByteArray();

            try
            {
               ostrm.close();
            }
            catch (IOException e)
            {
            }

            try
            {
               bytes.close();
            }
            catch (IOException e)
            {
            }
         }
         catch (IOException e)
         {
            e.printStackTrace(System.out);
         }
      }
      return results;
   }

P.S. This old code I dug out of the attic - Needs to be modernized

Romain Hippeau