There are only a few options to get XML out of an XmlDocument in .NET. There is innerHTML, outerHTML, Save, and WriteTo methods available. Someone recommending using the outerHTML which wrote all the information out correctly, but there was no formatting at all. VS.NET did not like this at all and would actually hang.
The only two options left is to Save and WriteTo. Saving an XmlDocument to the file system is easy. You have the following to choose from:
public virtual void Save( Stream );
public virtual void Save( string );
public virtual void Save( TextWriter );
public virtual void Save( XmlWriter );
public override void WriteTo( XmlWriter )
In all the examples they write to a file, but I need a string. I want to send the XmlDocument to the browser so it can be downloaded. There was numerous examples using the Console:
XmlTextWriter writer = new XmlTextWriter(Console.Out);
writer.Formatting = Formatting.Indented;
doc.WriteTo( writer );
writer.Flush();
Console.WriteLine();
I finally stumbled on an example that used StringWriter to convert the XmlDocument into a string.
XmlDocument xmlDoc = new XmlDocument;
xmlDoc.Load( "Test.xml");
Response.Clear();
//Set the type of file that will be sent.
Response.ContentType = "text/xml";
//These lines are here just for formatting the XML file so it is easier to read.
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.Indented;
xmlDoc.WriteTo(writer);
//Set the length of the file
Response.AppendHeader("Content-Length", sw.ToString().Length.ToString());
//Set the file name information.
Response.AppendHeader("Content-Disposition", "attachment; filename=Download.xml" );
//Send the actual XML.
Response.Write( sw.ToString() );
Response.End();
The key to this is using the StringWriter not StringBuilder.
This was just what I needed. Perfect. Thank you!!
Thank you very much for that post. I saved me a lot of time!
Thank you so much…..