I am trying to serialize an object(s) to an XML string. I want to do this without ever actually creating an .xml file. The way I do it works, and seems to be fine. I just want to make sure that there is not something I have overlooked. If anyone has a better way of doing it I would appreciate the help. Here is my code:
String
XmlizedString = null; XmlSerializer x = new XmlSerializer(Inv.GetType()); MemoryStream memoryStream = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);x.Serialize(xmlTextWriter, Inv);
memoryStream = (
MemoryStream)xmlTextWriter.BaseStream; UTF8Encoding encoding = new UTF8Encoding();XmlizedString = encoding.GetString(memoryStream.ToArray());
XmlizedString = XmlizedString.Substring(1);

Serialize object to string
Moumen
I tried like this:
XmlTextWriter who = new XmlTextWriter(@"c:\a\test.xml", Encoding.UTF8);
who.WriteRaw(XmlizedString);
who.Close();
I also tried this:
StreamWriter j = new StreamWriter(@"c:\a\test.xml");
j.Write(XmlizedString); j.Close();both gave that same error message. What would be the best way to deserilize this string back into an object THanks for all the help.
pm6262
Oh, it's Internet Explorer giving that error
The problem is that the XML file is stating that its encoding is in UTF-16, yet the file is written out using UTF-8.
Instead, use the following:
XmlTextWriter who = new XmlTextWriter(@"c:\a\test.xml", Encoding.Unicode);
itsnomihere
AKORNICH
How are you saving it to and loading it from a XML file (ie post code)
I tried just loading it into an XmlDocument and it worked fine.
bpjung
I just tried that and it worked. But when I wrote it back to an .xml file to see if everything was ok it gave an error: Any ideas I know I said I wouldnt write to xml file, but I am going to need this to be valid xml so I can deserialize it. I can load it into an xmldocument object. I will have to further test to see if it can be deserialized. Any idea why i cant write to .xml file.. thanks.
Switch from current encoding to specified encoding not supported. Error processing resource 'file:///C:/a/test.xml'. L...
skrewed
darkrevan
As XmlSerializer.Serialize accepts a TextWriter, you can simply use a StringWriter:
public static string SerializeToString(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
PoZZyX
You just need to work backwards, ie use a StringReader. You could also get tricky and using generics to avoid casting:
public static T SerializeFromString<T>(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xml))
{
return (T)serializer.Deserialize(reader);
}
}
This allows you do the following:
int value = 12;
string xml = SerializeToString(value);
value = SerializeFromString<Int32>(xml);
Console.WriteLine(value);