xml serialization via a memory stream

  • Thread starter Thread starter Martin
  • Start date Start date
M

Martin

G'day,

I have encountered a problem with serializing a class using xml
serialization and a memory stream.
what i am attempting to do is serialize a class and the read the serialized
string into an xml document.
However when I convert the memory stream to a string the first character
should seemingly not be there.
The code below will compile in a comsole application.

take a look at the string "XmlizedString " in the debugger or even wrote out
to the console window.

any ideas why that extra charcter is there before the well formed xml.

many thanks in advance.

cheers

martin.

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Xml;

using System.Xml.Serialization;

namespace ConsoleApplication

{

public class Vehicle

{

private Vehicle()

{

}

public Vehicle(string VIN, string Make, string Model, int Year, string
Owner)

{

this.VIN = VIN;

this.Make = Make;

this.Model = Model;

this.Year = Year;

this.Owner = Owner;

}

public string VIN;

public string Make;

public string Model;

private int Year;

private string Owner;

}

class Program

{

static void Main(string[] args)

{

Vehicle vehicle = new Vehicle("VIN", "Make", "Model", 2007, "Myself");

String XmlizedString = null;

MemoryStream memoryStream = new MemoryStream();

XmlSerializer xs = new XmlSerializer(typeof(Vehicle));

XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream,
Encoding.UTF8);

xs.Serialize(xmlTextWriter, vehicle);

memoryStream = (MemoryStream)xmlTextWriter.BaseStream;

UTF8Encoding encoding = new UTF8Encoding();

XmlizedString = encoding.GetString(memoryStream.ToArray());

Console.Write(XmlizedString);//<----Look at the value in the debugger there
is a strange charcater before the opening "<"

XmlDocument xmldoc1 = new XmlDocument();

xmldoc1.LoadXml(XmlizedString);//<----------Error.

}

}

}
 
You don't need to use the XmlTextWriter just change the code to something
similar to this:

using (MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer xs = new XmlSerializer(typeof(Vehicle));

xs.Serialize(memoryStream, vehicle);

XmlizedString =
System.Text.UTF8Encoding.UTF8.GetString(memoryStream.ToArray());
}
 
Back
Top