如何将异常对象序列化为xml字符串

JL.*_*JL. 2 c# xml exception

我想要类似的东西

try
 {
   //code here
 }
 catch (Exception ex)
  {
    stringXML = Exception.toXML(); 
  }
Run Code Online (Sandbox Code Playgroud)

这样stringXML的值就是

 <exception><message></message><innerException></innerException></exception>
Run Code Online (Sandbox Code Playgroud)

例如...

这怎么可能?

Mar*_*ell 9

这取决于您要编写多少代码.一种简单的方法是编写自己的对象并使用XmlSerializer:

[XmlRoot("exception"), XmLType("exception")]
public class SerializableException {
    [XmlElement("message")]
    public string Message {get;set;}

    [XmlElement("innerException")]
    public SerializableException InnerException {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

并将常规异常映射到此.但既然它很简单,也许XmlWriter就够了......

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();
}
Run Code Online (Sandbox Code Playgroud)