如何将异常对象序列化为xml字符串 [英] how to serialise exception object as xml string

查看:151
本文介绍了如何将异常对象序列化为xml字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想是这样

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



让stringXML的价值将是

so that the value of stringXML would be

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

例如...

如何这可能吗?

推荐答案

这取决于你想要多少代码编写。一个简单的方法是写自己的对象,并使用的XmlSerializer

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

和映射只是一个普通的异常到此。但由于它是简单,无论如何,也许的XmlWriter 是不够好...

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

这篇关于如何将异常对象序列化为xml字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆