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);
}
2

3 Answers 3

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();
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

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);
        }

Comments

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());
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.