It depends how much code you want to write. One simple approach would be to write your own object and use XmlSerializer
:
[XmlRoot("exception"), XmLType("exception")]
public class SerializableException {
[XmlElement("message")]
public string Message {get;set;}
[XmlElement("innerException")]
public SerializableException InnerException {get;set;}
}
and just map a regular exception into this. But since it is simple anyway, maybe XmlWriter
is good enough...
public static string GetXmlString(this Exception exception)
{
if (exception == null) throw new ArgumentNullException("exception");
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw))
{
WriteException(xw, "exception", exception);
}
return sw.ToString();
}
static void WriteException(XmlWriter writer, string name, Exception exception)
{
if (exception == null) return;
writer.WriteStartElement(name);
writer.WriteElementString("message", exception.Message);
writer.WriteElementString("source", exception.Source);
WriteException(writer, "innerException", exception.InnerException);
writer.WriteEndElement();
}