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:

MySerializableClass myObject = new MySerializableClass(); 
// Insert code to set properties and fields of the object. 
XmlSerializer mySerializer = new
XmlSerializer(typeof(MySerializableClass));
// To write to a file, create a StreamWriter object. 
StreamWriter myWriter = new StreamWriter("myFileName.xml"); 
mySerializer.Serialize(myWriter, myObject); 

How do I make a similar code that would give me a string or an XML
Document that contains the XML-serialized object?
0
kjems (4)
8/6/2004 11:21:45 AM
dotnet.xml 7266 articles. 0 followers. Follow

3 Replies
511 Views

Similar Articles

[PageSpeed] 6


Kristian Kjems wrote:

> This is the example from MSDN where an object is serialized to a
> filestream:
> 
> MySerializableClass myObject = new MySerializableClass(); 
> // Insert code to set properties and fields of the object. 
> XmlSerializer mySerializer = new
> XmlSerializer(typeof(MySerializableClass));
> // To write to a file, create a StreamWriter object. 
> StreamWriter myWriter = new StreamWriter("myFileName.xml"); 
> mySerializer.Serialize(myWriter, 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(typeof(Person));

     StringWriter stringWriter = new StringWriter();

     xmlSerializer.Serialize(stringWriter, p1);

     string serializedXML = stringWriter.ToString();

     Console.WriteLine(serializedXML);


> 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(typeof(Person));

     MemoryStream memStream = new MemoryStream();

     StreamWriter streamWriter = new StreamWriter(memStream);


     xmlSerializer.Serialize(streamWriter, p1);

     memStream.Position = 0;

     StreamReader streamReader = new StreamReader(memStream);

     XmlDocument serializedXML = new XmlDocument();

     serializedXML.Load(streamReader);

     Console.WriteLine(serializedXML.OuterXml);
-- 

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

0
mahotrash (1777)
8/6/2004 2:52:56 PM
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.

0
kjems (4)
8/7/2004 11:34:41 AM
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 'AbstractXMLObject'"

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

abstract public class AbstractXMLObject
{	
 public string XML
 {
  get
   {				
    XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
    StringWriter stringWriter = new StringWriter();
    xmlSerializer.Serialize(stringWriter,this);
    return stringWriter.ToString();
   }
  set
  {
   XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
   StringReader stringReader = new StringReader(value);	
   this = xmlSerializer.Deserialize(stringReader);        
  }
 }
}

0
kjems (4)
8/10/2004 3:12:52 PM
Reply:

Similar Artilces:

Problem opening serialized file via Open command associated with file type
I have an SDI MFC application that produces a serialized project file via CObject's serialization support. The application can read the file from within the application just fine. The installer registers the program and the file extension properly and associates the file type with the application. However, when I double click on the project file, the application generates an "Unexpected File Format" message. Is there a method in the document class that needs to added to handle this functionality? I want to try and debug the problem but not sure how to invoke the debugg...

Convert string to double newbie question
I tried looking in help for this but what it said didn't work from help to cast from one type to another //i = (int) d; // An explicit conversion, or "cast" in my code i tried: (tbDepth is a textbox on a form) private double m_dDepth =0; m_dDepth = (double)tbDepth.Text; compile error Cannot convert type 'string' to 'double' how do i convert a string representing a double to a double? thanks Mark Hi! "mp" <nospam@thanks.com> schrieb im Newsbeitrag news:OMZlPAc0KHA.752@TK2MSFTNGP04.phx.gbl... > private double m_...

string functions
Hi there, does anybody know how to extract the domain name from an email address. I have a list of email address in column A, in coloumn I would like to output the domain for each row. e.g. you@yourcompany.com (column A) would return yourcompany.com (column B) any help on how this could be done, assuming each row contains a valid email address. Thanks in advance Drew Kennelly Hi try =MID(A1,FIND("@",A1)+1,1024) -- Regards Frank Kabel Frankfurt, Germany "Drew Kennelly" <drew@conceptiondesigns.co.nz> schrieb im Newsbeitrag news:rmWnd.7992$9A.176663@news.xt...

XPath problem with dateTime strings comparison
Hello, I've got an XML file saved from DataSet. One table has datetime column (datatype - xs:dateTime). XML file fragment for example: <Root> <Element>2004-03-15T00:00:00.0000000+01:00</Element> <Element>2004-03-16T00:00:00.0000000+01:00</Element> <Element>2004-03-17T00:00:00.0000000+01:00</Element> <Element>2004-03-18T00:00:00.0000000+01:00</Element> </Root> I'm trying to get MyXmlNodeList using MyXmlDataDocument.DocumentElement.SelectNodes(MyXPathString) method, where MyXPathString, for example, should loo...

Finding a string/using adjacent data question
It's a convuluted question that I hope has an easy answer. I'm rather new to Excel formulas, so I've been trying to find stuff about this on the internet but with not much luck. If anyone can help me at all I would greatly appreciate it. I have text strings in column A, A2-A335. I have numerical values that correspond to each text string in columns B-O. What I'm hoping to do is run a search for a given text string in column A and then use the numerical values in D, H, and O for further calculations. I want to be able to type in a name in column Q (for example) and have the f...

Would like to locate a text box based on a search string and copy
I have a worksheet with several text boxes on it. Based on a radio button selection I need to search through all of the text boxes for for a text string and display that box on the worksheet where the radio button is or copy it based on some reference. I use text boxes from the Draw toolbar because they are highly formatable. Another method may be acceptable as long as I can format text. Thank you. Hello: Can I assume that your Textboxes are on a regular worksheet and not a form opened with the VBA command MyForm.Show? Also, which toolbox did you use: Forms or Control Tool...

How to fix "An object cannot be found" problem?
I cannot use M/S Outlook email because it states, "An object cannot be found"? How to fix? On Fri, 31 Dec 2004 09:29:03 -0800, Jim - Houston wrote: > I cannot use M/S Outlook email because it states, "An object cannot be > found"? How to fix? See if http://support.microsoft.com/default.aspx?scid=kb;en-us;312354 helps. -- Jeff Stephenson Outlook Development This posting is provided "AS IS" with no warranties, and confers no rights ...

Does Excel support mixed formatting of a string in a formula cell, yet?
Excel is one of the most spectacular apps ever created. But one feature I really need is mixed formatting of a string whose cell is a formula. By mixed formatting I mean, you know, making selected (as opposed to all) character(s) of the string bold, italic, a different color, sub- or superscripted, etc. In Excel 2002 you cannot do that in a formula cell (right?). In edit mode, the user would, say, press F9 to display the calc'ed string, selectively format it as usual, then cancel edit. Excel would save the formatting as a separate mask. What could be easier? The user would ...

How will I do Excel user-defined function to extract letters from string
How will I extract letters from this string like... to: AB-123456-45 AB BCD-678901-23 BCD E-23454 E if I this bottom code extract numbers from a the same string: Function ExtractNum(rCell As Range) Dim iCount As Integer, i As Integer Dim sText As String Dim lNum As String sText = rCell For iCount = Len(sText) To 1 Step -1 If IsNumeric(Mid(sText, iCount, 1)) Then i = i + 1 lNum = Mid(sText, iCount, 1) & lNum End If If i = 1 Then lNum = CInt(Mid(lNum, 1, 1)) Next iCount ExtractNum ...

Outgoing emails showing user logon name instead of Users Full Name
Hi, I am using Exchange 2003 with Outlook (Office 2003 Pro ), and tried the "Display Name" and the "Simple Display Name" in the users properties, but I still get the users account name when emails are sent to external accounts. Is there any other way to do this? -- MCSE 2000 ...

Excel sheet (OLE object) sometimes open on the form sometimes in E
Hello there, I have an Excel sheet (OLE object in the table) on a form , I have setup the Property in "Auto Activate" as Double-Click , so when I double click the object the sheet open. But sometime the object appears on the form as an Excel Icon - then when I double click it open in Excel - that is what I want. But sometime it appears as a table of data and when I double click it open on the form - I want to avoid that and instead always have the sheet open in excel. Any idea? Many many thanks, Dan Hi Dan, By default, you can directly double click the OLE Ob...

Serial number notes
We would like to have Serial Number level notes to track particular issues with that item/serial number such as warranty support issues, part replacement and warranty registration. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" in the message pane. http://www.microsoft.com/Businesssolut...

Extract string from cell
I have a column of data as follows: JOHN SMITH#INTERN#3154#jsmith@xyz.com# |\ JANE DOE#SPECIALIST#2312#jdoe@xyz.com# |\ . . . I would like to extract the e-mail alias, in the above examples it would be "jsmith" and "jdoe". I'm familiar with the LEFT, MID, and RIGHT functions, but those won't work because the location of the string I want t extract is not fixed. Any ideas would be appreciated. Thanks! If it is always the third # that is preceding the email and there is always a # |\ at the end...

Extracting a word form a text string
Hi I run Excel 2K I have a number of text strings with each string containing a key word which is located in different postitions of each text string. I need a formula that extracts only that key word from the text string. Lets say the word is TEST Thanks On Oct 21, 8:46=A0am, John Calder <JohnCal...@discussions.microsoft.com> wrote: > Hi > > I run Excel 2K > > I have a number of text strings with each string containing a key word wh= ich > is located in different postitions of each text string. > > I need a formula that extracts only that key word from the...

add blank to a string generated with a workflow
Hello, I generated a workflow rule, that creates a salutation for letters consisting of gender, name, language and academic title. It works great, but the whole salutation gets created without spaces. Like "DearMr.Hudson" Does anyone has an idea how to create a workflow rule, that adds a blank between those words? It's not possible to add a static value and fill in a blank. If you do that, CRM interprets the blank as NULL and adds nothing. Any Ideas? Thanks for your help! Simon Have you tried putting in the HTML for a blank space (see below) ' ' (minus the qu...

object address and long
Hi, Does an address of any object fit in a long, or what type is suitable for this ? Hi RAN, A long is 32 bits, so it does have enough bits for a pointer to address = and object. But, a long is not suitable for assigning an address, it's supposed to = be used just for an integer value. You could use it, but you get warnings and such. So, instead use LONG_PTR. WPARAM and LPARAM are examples of type LONG_PTR. LPVOID is also suitable as a pointer to any type. REF: http://msdn2.microsoft.com/en-us/library/aa383751.aspx HTH, "RAN" <nijenhuis@wish.nl> wrote in message = n...

CSV file displaying ###### instead of $nn,nnn
Hi I used PHP's 'fgetcsv' (http://us3.php.net/manual/en/function.fgetcsv.php) to write data to a ..csv file. The data pretty much formatted when I opened it in 'Context' (http://www.context.cx/) but when opened in Excel 2003, one column which contains data like *"$105,138"* is showing as *########*. When the cell is hovered over it shows *$105,138* in the tip but shows *105138* in the top textbox (the one next to fx label) How do I 'tell' Excel to display *$105,138* instead of *########* ? Thanks -- anjanesh Freelance Developer --------------------...

can a reminder be sent as an email instead of a popup?
I'd like the reminders to be sent to my email account's inbox rather than pop up and interrupt me. Can that be done? Mr. Not without a third party program. --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. All unsolicited mail sent to my personal account will be deleted without reading. After furious head scratching, Mr . . asked: | I'd like the reminders to be sent to my email account's inbox rather | than pop up and interrupt me. | | Can that be done? | | Mr. "Mr . ." <deleteme@sbc.net> wrote in messag...

Unhandled Object exception #2
I have a client that is getting the following message every hour: Unhandled object exception: Operation aborted: Exception_Class_Object_Exception ExceptionSubClass=-2147467260 They are running Dyanamics GP version 9.0 Thank you. When do they get this error? Doing what? Executing what function? Does it happen even when they are not doing anything? Does the error just show up randomly? Best regards, -- MG.- Mariano Gomez, MIS, MCP, PMP Maximum Global Business, LLC http://www.maximumglobalbusiness.com "Stan Mah" wrote: > I have a client that is getting the following messag...

Error: Could not install custom action. Object not found.
What do I need to do getting this error message when trying to create a new email or calendar entry in Outlook 2007? Thanks.... Sonja;114099 Wrote: > What do I need to do getting this error message when trying to create a > new email or calendar entry in Outlook 2007? Did this error just start occurring? If so, what changed on your PC just before the error started. If it has always appeared since installing Outlook, describe exactly how you installed Outlook and how you created your mail profile. -- Brian Tillman [MVP-Outlook] http://forums.slipstick.com ...

xml serialization using generic list fails
I've got a gaming framework i'm building and i want to save myself the trouble of reading and writting the complete game data to a custom file and load/save it to an XML file but i'm getting problem serializing my stuff to XML when it comes to collections. I'm currently using .net2 with generic lists to prevent users putting all sorts of stuff in the arrays (Although im sure i'll be the only user of the classes but not the game, anyway). So i need to be able to serialize a complex object structure that looks like this (simplified) : Game - Hero - InitialDirection - Scene...

Convert string to uniqueidentifier?
I have a View with a varchar(36) which hold string guid's. I am trying to import that data over to another db-table into a uniqueidentifier column. The import wizard errors out : *** the column is called Customer on both sides *** Error 0xc02020c5: Data Flow Task 1: Data conversion failed while converting column "Customer" (101) to column "Customer" (229). The conversion returned status value 2 and status text "The value could not be converted because of a potential loss of data.". (SQL Server Import and Export Wizard) I thought that st...

Preventing memory and resource leaks with GDI Objects ???
I am have built a general purpose bitmap/image handling class and want to add TextOut() capability to this class. To do this I must convert some of my GDI local function variables into GDI object member variables. This means that I must be able to re-use several GDI objects, instead of constructing them and destroying them after a single use. What issues are raised with resource and memory leaks by using CDC and CBitmap objects? How are these issues mitigated? You will have to manage the resources somehow and someplace, but I don't think it matters how or where. ...

blank instead of DIV/0!
I have a formula like this =A1/COUNT(F3:F124) When cells F3:F124 are emty, my formula returns #DIV/0! Can that be made a blank cell instead of #DIV/0! ? rgd Bill Gras Hi! Here's one way: =IF(COUNT(F3:F124)=0,"",A1/COUNT(F3:F124)) Biff >-----Original Message----- >I have a formula like this =A1/COUNT(F3:F124) >When cells F3:F124 are emty, my formula returns #DIV/0! >Can that be made a blank cell instead of #DIV/0! ? > >rgd Bill Gras >. > Try this one too. (Assume Cell with formula is A1) Go to 'Conditional Formatting' for this cell , In...

Insert XML string into XML File: Part 2
Thanks to some good help from a previous post, I have been able to create well formed xml as part of a report logger app. However, I still have a small problem. When I add new xml to the log file, the new nodes are appended to the original file. What I really want is for the log file to grow as "report nodes" are added. Also, I am a bit concerned about performance, particularly as the file grows in size. I must write to an xml file (vs. a database) and am trying to understand the best way to do this. I prefer to not use "temp files" and would like to just modify the ...