Popular Posts
- how2: Use QueryString (that stuff after *.aspx?) in a URL
- how2: Convert an Xml Document to a string with C#
- Starting a new chapter @ Microsoft
- how2: detect 32 or 64 bit operating system
- Revive your zune 30's dead battery
Tags
books coding dogs funnies links microsoft one-liners parenthood ramblings sports technology testing video-games workplace
Subscribe
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>
- static string GetXmlString(string strFile)
- {
- // Load the xml file into XmlDocument object.
- XmlDocument xmlDoc = new XmlDocument();
- try
- {
- xmlDoc.Load(strFile);
- }
- catch (XmlException e)
- {
- Console.WriteLine(e.Message);
- }
- // Now create StringWriter object to get data from xml document.
- StringWriter sw = new StringWriter();
- XmlTextWriter xw = new XmlTextWriter(sw);
- xmlDoc.WriteTo(xw);
- return sw.ToString();
- }
<------------<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: coding


1819 comment(s)
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.
Great! Thanks for the code, it helped me a lot! :)