0

I have created a streamExtension where i can simply serialize and deserialze the stream from and to an xml file, the code looks as follows:

/// <summary>
/// Contains the logic for streaming extensions.
/// </summary>
public static class StreamExtensions
{
    /// <summary>
    /// Serialize an object.
    /// </summary>
    /// <typeparam name="T">The type of the object that gets serialized.</typeparam>
    /// <param name="stream">The stream to which the bytes will be written.</param>
    /// <param name="serializableObject">The object that gets serialized.</param>
    public static void SerializeObject<T>(this Stream stream, T serializableObject) where T : IXmlSerializable
    {
        var xmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8);
        xmlTextWriter.Formatting = Formatting.Indented;
        xmlTextWriter.IndentChar = ' ';
        xmlTextWriter.Indentation = 4;

        var serializer = new XmlSerializer(typeof(T));

        serializer.Serialize(xmlTextWriter, serializableObject);

        xmlTextWriter.Close();
        stream.Close();
    }

    /// <summary>
    /// Deserialize a stream and return the object.
    /// </summary>
    /// <typeparam name="T">The type of the object that returns from the deserialization.</typeparam>
    /// <param name="stream">The stream which contains the bytes to deserialize.</param>
    /// <returns>The object recovered.</returns>
    public static T DeserializeObject<T>(this Stream stream)
    {
        var xmlTextReader = new XmlTextReader(stream);
        var serializer = new XmlSerializer(typeof(T));

        var result = (T)serializer.Deserialize(xmlTextReader);

        xmlTextReader.Close();
        stream.Close();

        return result;
    }
}

2 very simple (and if I may say so: elegant) methods for serializing and deserializing.

I am using this class as a test:

/// <summary>
/// A serializable class for testing purposes.
/// </summary>
public class SerializableXmlTest : IXmlSerializable
{
    #region Fields
    private string mTestString = string.Empty;
    #endregion

    #region Properties
    /// <summary>
    /// Gets or sets the configuration for this simulation.
    /// </summary>
    /// <value>The configuration for this simulation.</value>
    public string TestString
    {
        get
        {
            return mTestString;
        }

        set
        {
            mTestString = value;
        }
    }
    #endregion

    #region XML serialization region
    /// <summary>
    /// Write the extra information to an XML stream.
    /// </summary>
    /// <param name="writer">Writer to write to.</param>
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement(MethodBase.GetCurrentMethod().DeclaringType.Name);
        writer.WriteAttributeString("TestString", this.TestString);
        writer.WriteEndElement();
    }

    /// <summary>
    /// Read the extra information from an XML stream.
    /// </summary>
    /// <param name="reader">Reader to read from.</param>
    public void ReadXml(XmlReader reader)
    {
        if ((reader.MoveToContent() == XmlNodeType.Element) && (reader.Name == MethodBase.GetCurrentMethod().DeclaringType.Name))
        {
            reader.Read();
            this.TestString = reader.GetAttribute("TestString");
        }

        reader.ReadEndElement();
    }

    /// <summary>
    /// This method is reserved when implementing the IXmlSerializable interface.
    /// </summary>
    /// <returns>An XmlSchema that describes the XML representation of the
    /// object that is produced by the WriteXml method and consumed by the
    /// ReadXml method.</returns>
    public XmlSchema GetSchema()
    {
        return null;
    }
    #endregion
}

And this is the code in my unit test:

/// <summary>
/// Test the stream extension class for normal function.
/// </summary>
[Test]
public void TestStreamExtension()
{
    File.Delete(mFileName);
    var testObject = new SerializableXmlTest();
    testObject.TestString = "Test";

    Stream saveFileStream = new FileStream(mFileName, FileMode.OpenOrCreate);
    saveFileStream.SerializeObject(testObject);

    Stream openFileStream = new FileStream(mFileName, FileMode.OpenOrCreate);
    var testObjectClone = openFileStream.DeserializeObject<SerializableXmlTest>();
    Assert.IsTrue(testObject.TestString.Equals(testObjectClone.TestString));
    }

And the xml file that is ouputted:

<?xml version="1.0" encoding="utf-8"?>
<SerializableXmlTest>
    <SerializableXmlTest TestString="Test" />
</SerializableXmlTest>

However there are a few things i don't understand and at least one of them is definitely wrong (I think)

The first thing is I expected my xml file to look like this:

<?xml version="1.0" encoding="utf-8"?>
<SerializableXmlTest TestString="Test" />

But I can understand if you need the separate start and end element.

The second thig when trying to read It the first element the reader lands on is (as expected) <SerializableXmlTest> However if I then proceed to do a reader.Read() or reader.ReadStartElement() the debugger tells me it is currently reading:

{Whitespace, Value="\r\n    "}.

Where does this come from? why is it reading a new line character? Obviously when i then use an other reader.Read() i do get to the <SerializableXmlTest TestString="Test" /> line in my xml file.

What am I doing wrong?

P.s. It might be wise to tell you i changed the serialize and deserialze methods a bit, (they used to be working) but the serialize used only the xmlTextWriter and not the XmlSerializer. and the Deserialize method used a stream reader instead of XmlTextReader. but for the sake of trying to make them the same i got this problem which i can't seem to figure out.

Extra question: should I even use the XmlTextReader and writer? I could just as well pass the stream I get as method parameter to the serializer couldn't I?

3
  • Side note: using using would make your serialization helpers not only elegant but also correct (and match everyone else implementation). Nov 4, 2015 at 7:45
  • Thanks, changed it :)
    – Vincent
    Nov 4, 2015 at 7:55
  • Don't use XmlTextWriter/XmlTextReader classes. Starting with the .NET Framework 2.0 recommends use the XmlWriter/XmlReader instead. Use XmlWriterSettings/XmlReaderSettings to configure them. Nov 4, 2015 at 10:21

1 Answer 1

1

A few things.

1) The failure with the serializer

XmlSerializer.Serialize(stream, object)

already writes the encoding of the file and the start element. That's why you get the strange output. Reduce your WriteXML method to just open the stream, and let the serializer do the rest. That will fix your written XML file.

2) The read of \r\n

There are currently 2 ways to access XML data in .NET

  • XmlReader \ XmlWriter
  • XmlFile

When you use the XmlReader you will have way more access to a XML file and way more deep. That means on the other hand, that some automations get lost. The XmlReader.Read() works completely correct. First he finds an < sign. So now he knows to read till he finds > an end tag. Then u tell him to read again. Now he reads an \r\n sign. Now he knows that he has to stop, because you told him to read only 1 character and he didn't found < a beginning tag.

Hope this helps

5
  • Is there a way to make Serialize not write the start and end element but do it my self?
    – Vincent
    Nov 4, 2015 at 8:09
  • I know that u can create ur own mappings and then create out of them a serializer. But I think this will not change, that the serializer will write all needed for a valid xml file. What is actually the reason for the need to not let the serializer handle that? maybe there is a better solution Nov 4, 2015 at 8:52
  • Because I also use abstract classes and you either need those [] tags above a list of abstract classes to indicate which classes there are or you need to read/write the xml your self. the company decided against the tags because that would mean, every time you create a new derived class you need to open the abstract class and add a tag there. The less we need to open and change old files the better.
    – Vincent
    Nov 4, 2015 at 9:33
  • Sr but for this point, I currently have no answer. Maybe it is possible to teach the serializer this behavior, but from my point of view, I would go another way. I would take the serializer, write a class with it using the serializer and manipulate the file/stream afterwards to my needs. Nov 4, 2015 at 9:36
  • Or maybe not use xmlSerializer but just the xmlTextReader and writer.
    – Vincent
    Nov 4, 2015 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.