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

标签 c# xml exception

我想要类似的东西

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

这样 stringXML 的值就是

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

例如……

这怎么可能?

最佳答案

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

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

    [XmlElement("innerException")]
    public SerializableException InnerException {get;set;}
}

然后将常规异常映射到其中。但无论如何它都很简单,也许 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();
}

关于c# - 如何将异常对象序列化为 xml 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1153011/

相关文章:

java - 遇到 java.net.BindException : Address already in use (Bind failed) on server- client socket app

java - 每次java.lang.exception.getCause()都为null

除特定单词外的正则表达式

c# - 如何对 Windows API 常量进行分组

c# - .NET 引用源中的缩写词 EE 是什么意思?

java - 如何使用 xquery 在 java 中处理非常大的 xml 文件,如 150mb

android - Kotlin 中的 STRING_TOO_LARGE 字符串

c# - EF映射一对一可选

C#减慢随机数GUI显示

.net - 使用 System.Xml.XmlDocument 解析 vcxproj