dirtyDogStink

how2: Convert an Xml Document to a string with C#

Friday, February 18 2005

As part of my current project, I am taking an Xml document and inserting it into a text field in a SQL 2000 database.  I found the few lines of code I needed (here), but thought I'd add them here too for reference purposes.

As stated in the link above, "this is kind of a handy utility because when you call ToString method on XmlDocument object, it does not return you its contents but it returns the full class name System.Xml.XmlDocument."

When called by another method, the method below will return the string for you to manipulate.

<------------<start code here>

  1. static string GetXmlString(string strFile)
  2. {
  3.         // Load the xml file into XmlDocument object.
  4.         XmlDocument xmlDoc = new XmlDocument();
  5.         try
  6.         {
  7.                 xmlDoc.Load(strFile);
  8.         }
  9.         catch (XmlException e)
  10.         {
  11.                 Console.WriteLine(e.Message);
  12.         }
  13.         // Now create StringWriter object to get data from xml document.
  14.         StringWriter sw = new StringWriter();
  15.         XmlTextWriter xw = new XmlTextWriter(sw);
  16.         xmlDoc.WriteTo(xw);
  17.         return sw.ToString();
  18. }   
<------------<end code here>
 
I didn't use the exact method above because I only need to do this once in my application...so I just added lines 14 - 16 to convert my XmlDocument.  It worked like a charm!
 
Hope this helps!  Happy coding!
Tags:

1819 comment(s)

Bruno wrote on January 23, 2008

Thank you very much, this code helped me a lot. I was trying to use memory stream before and having a pretty hard time trying to convert it to the correct string encoding.

@Bruno: Glad I could help.

DrOverflow wrote on January 23, 2008

Great! Thanks for the code, it helped me a lot! :)