Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialise exception object as xml string

Tags:

c#

exception

xml

I want something like

try
 {
   //code here
 }
 catch (Exception ex)
  {
    stringXML = Exception.toXML(); 
  }

so that the value of stringXML would be

 <exception><message></message><innerException></innerException></exception>

For example...

How is this possible?

like image 420
JL. Avatar asked Jan 21 '26 04:01

JL.


1 Answers

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();
}
like image 165
Marc Gravell Avatar answered Jan 22 '26 17:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!