Tuesday, June 24, 2008

Saving an XPathDocument or XmlDocument to a File in ASP.NET

Today I was working on a class that was returning an XPathDocument representation of an XML document and I needed to save it to a file. I switched the class to return an XmlDocument ... and the reason for that should be obvious from the two code samples below.

Here's how I saved an XPathDocument to an XML file:

// myItems[0] is from a generic List<XPathDocument> list
XPathDocument document = myItems[0];
// Feels like there should be an easier way to do this.
XPathNavigator documentNav = document.CreateNavigator();
XmlTextWriter writer = new XmlTextWriter(
Server.MapPath(temporaryFiles + "/" +
fileId + ".xml"), System.Text.Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 3;
writer.WriteStartDocument();
writer.WriteNode(documentNav, true);
writer.WriteEndDocument();
writer.Close();

Now here's how I saved an XmlDocument to an XML file:

// myItems[0] is from a generic List<XmlDocument> list
XmlDocument document = myItems[0];
document.Save(
Server.MapPath(temporaryFiles + "/" + fileId + ".xml"));

1 comment:

trystan said...

Another method of doing this (.NET 2.0+) is as follows...

// Create XpathNaviagtor instances from XpathDoc instance.
XPathNavigator objXPathNav = xpathDoc.CreateNavigator();

// Create XmlWriter settings instance.
XmlWriterSettings objXmlWriterSettings = new XmlWriterSettings();
objXmlWriterSettings.Indent = true;

// Create disposable XmlWriter and write XML to file.
using (XmlWriter objXmlWriter = XmlWriter.Create(CompanyReportFilePath, objXmlWriterSettings))
{
objXPathNav.WriteSubtree(objXmlWriter);
objXmlWriter.Close();
}