2

I am wanting to be able to create an XML document to save to a SQL database from an Exception object. Is there a way to easily convert an exception object into an XML document? I want to be able to do something like:

public void WriteError(Exception ex)
{
    var doc = new XmlDocument();
    doc.Load(ex);
    sql.Insert(doc);
}
MrBilly222
  • 65
  • 5
  • You may check this https://seattlesoftware.wordpress.com/2008/08/22/serializing-exceptions-to-xml/ – Navoneel Talukdar Jan 12 '17 at 17:22
  • May have been answered here [How to Serialize an Exception Object in C#](http://stackoverflow.com/questions/486460/how-to-serialize-an-exception-object-in-c) – RamblinRose Jan 12 '17 at 20:35

3 Answers3

1

What you're looking for is XmlSerializer. Serializing is changing to string, the XmlSerializer takes it one step further. I use an extension method that writes the generated XML to a file, but you can adapt it for your own needs:

public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
    {
        TextWriter writer = null;
        try
        {
            var serializer = new XmlSerializer(typeof(T));
            writer = new StreamWriter(filePath, append);
            serializer.Serialize(writer, objectToWrite);
        }
        finally
        {
            if (writer != null)
                writer.Close();
        }
    }
Forklift
  • 949
  • 8
  • 20
1

Using xml linq :

       public static void WriteError(Exception ex)
        {
            XDocument doc = new XDocument("Error", new object[] {
                new XElement("message", ex.Message),
                new XElement("stacktrace", ex.StackTrace),
                new XElement("helplink", ex.HelpLink)
            });

            sql.Insert(doc);
        }
jdweng
  • 33,250
  • 2
  • 15
  • 20
0

Here's how to do it with XmlSerializer as @Forklift suggested:

public void WriteError(Exception ex)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Exception));
    using (var memoryStream = new MemoryStream()) {
        xmlSerializer.Serialize(memoryStream, ex);
        var streamReader = new StreamReader(memoryStream);
        sql.Insert(streamReader.ReadToEnd());
    }
}