473,809 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I serialize an object to a string instead of a stream?

This is the example from MSDN where an object is serialized to a
filestream:

MySerializableC lass myObject = new MySerializableC lass();
// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new
XmlSerializer(t ypeof(MySeriali zableClass));
// To write to a file, create a StreamWriter object.
StreamWriter myWriter = new StreamWriter("m yFileName.xml") ;
mySerializer.Se rialize(myWrite r, myObject);

How do I make a similar code that would give me a string or an XML
Document that contains the XML-serialized object?
Nov 12 '05 #1
3 52282


Kristian Kjems wrote:
This is the example from MSDN where an object is serialized to a
filestream:

MySerializableC lass myObject = new MySerializableC lass();
// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new
XmlSerializer(t ypeof(MySeriali zableClass));
// To write to a file, create a StreamWriter object.
StreamWriter myWriter = new StreamWriter("m yFileName.xml") ;
mySerializer.Se rialize(myWrite r, myObject);

How do I make a similar code that would give me a string
You should be able to serialize to a StringWriter instead of a StreamWriter:

Person p1 = new Person();
p1.Name = "Kibo";

XmlSerializer xmlSerializer = new XmlSerializer(t ypeof(Person));

StringWriter stringWriter = new StringWriter();

xmlSerializer.S erialize(string Writer, p1);

string serializedXML = stringWriter.To String();

Console.WriteLi ne(serializedXM L);

or an XML
Document that contains the XML-serialized object?


That should work too by serializing to a memory stream and loading the
XmlDocument from that:

Person p1 = new Person();
p1.Name = "Kibo";

XmlSerializer xmlSerializer = new XmlSerializer(t ypeof(Person));

MemoryStream memStream = new MemoryStream();

StreamWriter streamWriter = new StreamWriter(me mStream);
xmlSerializer.S erialize(stream Writer, p1);

memStream.Posit ion = 0;

StreamReader streamReader = new StreamReader(me mStream);

XmlDocument serializedXML = new XmlDocument();

serializedXML.L oad(streamReade r);

Console.WriteLi ne(serializedXM L.OuterXml);
--

Martin Honnen
http://JavaScript.FAQTs.com/

Nov 12 '05 #2
Cheers mate, was exactly the kind of information I was looking for.
Had been searching for the C++ stringstream equivalent in C#, but did not
know it was called StringWriter.

Nov 12 '05 #3
With the information given to me in this thread I made an abstract class
that if inherited from will be able to return the current object as an XML
serialized string:
The "get" is working, but the last line is "set" is not.
I get these two not surprisingly error messages from VS.Net:
"Cannot assign to '<this>' because it is read-only"
"Cannot implicitly convert type 'object' to 'AbstractXMLObj ect'"

Is there any nifty way, the fundamental idea of "set" can be possible
anyway or does it strive against fundamental principles?

abstract public class AbstractXMLObje ct
{
public string XML
{
get
{
XmlSerializer xmlSerializer = new XmlSerializer(t his.GetType());
StringWriter stringWriter = new StringWriter();
xmlSerializer.S erialize(string Writer,this);
return stringWriter.To String();
}
set
{
XmlSerializer xmlSerializer = new XmlSerializer(t his.GetType());
StringReader stringReader = new StringReader(va lue);
this = xmlSerializer.D eserialize(stri ngReader);
}
}
}

Nov 12 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
8894
by: films | last post by:
I understand the concept. Serialization of a class will add all the sub-objects of the class to the stream if there are also serializible. So say I have: class Author {
2
2146
by: nick | last post by:
Is it recommended to serialize a custom object when putting it in session? I have a User object with properties ID, FirstName, LastName, and an array of Permissions which I would like to keep in session. Should I first serialize it to put it in session? I read that this is not necessary, but I'm wondering about memory usage and performance. I realize that serializing/deserializing the object will take time, but will the serialized object...
2
1362
by: Marcel Balcarek | last post by:
Does anyone have an example of serializing an object to a database table?
6
20108
by: Hayato Iriumi | last post by:
I'm looking for a way to convert String to Stream. I don't want to have to write the string out to a file to get the stream. Does anyone know how? TIA
3
3153
by: MMiGG | last post by:
Hi Our project need parse JAVA serialized object string in C, has any library? Thanx
4
34135
by: Evan Camilleri | last post by:
How can I trasform (as fast as possible) an object to a binary memory stream? Evan
2
5353
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi Is there any way to Read an INIFile from a string or Stream instead of a physical file ??? I want to read the INIFile into a string then store in a db but when I read the string from the db or save string to the db I don't want to have to copy the string to a file to use the WritePrivateProfileString and GetPrivateProfileString. Is there a way around this instead of writing my own class to operate on a string or stream ???
1
2203
by: pavankumar106 | last post by:
hi can anyone tell me how to convert a string to stream?
5
8427
by: labmonkey111 | last post by:
I have a table in SQLServer with a varchar field set to NOT NULL, with a default value of the empty string. This table is linked in access, and the field is linked to a text box on a form. When I attempt to edit that field, all is good unless I need to delete everything in the text box and return it to the default state of the empty string, Access complains: "You tried to assign the NULL value to a variable that is not a variant data type". I...
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10640
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10387
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7662
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5689
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.