簡體   English   中英

如何將異常對象序列化為xml字符串

[英]how to serialise exception object as xml string

我想要類似的東西

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

有人已經寫了一篇關於它的博客文章

using System;  
using System.Collections;  
using System.Linq;  
using System.Xml.Linq;  

/// <summary>Represent an Exception as XML data.</summary>  
public class ExceptionXElement : XElement  
{  
    /// <summary>Create an instance of ExceptionXElement.</summary>  
    /// <param name="exception">The Exception to serialize.</param>  
    public ExceptionXElement(Exception exception)  
        : this(exception, false)  
    { }  

    /// <summary>Create an instance of ExceptionXElement.</summary>  
    /// <param name="exception">The Exception to serialize.</param>  
    /// <param name="omitStackTrace">  
    /// Whether or not to serialize the Exception.StackTrace member  
    /// if it's not null.  
    /// </param>  
    public ExceptionXElement(Exception exception, bool omitStackTrace)  
        : base(new Func<XElement>(() =>  
        {  
            // Validate arguments  

            if (exception == null)  
            {  
                throw new ArgumentNullException("exception");  
            }  

            // The root element is the Exception's type  

            XElement root = new XElement  
                (exception.GetType().ToString());  

            if (exception.Message != null)  
            {  
                root.Add(new XElement("Message", exception.Message));  
            }  

            // StackTrace can be null, e.g.:  
            // new ExceptionAsXml(new Exception())  

            if (!omitStackTrace && exception.StackTrace != null)  
            {  
                root.Add  
                (  
                    new XElement("StackTrace",  
                        from frame in exception.StackTrace.Split('\n')  
                        let prettierFrame = frame.Substring(6).Trim()  
                        select new XElement("Frame", prettierFrame))  
                );  
            }  

            // Data is never null; it's empty if there is no data  

            if (exception.Data.Count > 0)  
            {  
                root.Add  
                (  
                    new XElement("Data",  
                        from entry in  
                            exception.Data.Cast<DictionaryEntry>()  
                        let key = entry.Key.ToString()  
                        let value = (entry.Value == null) ?  
                            "null" : entry.Value.ToString()  
                        select new XElement(key, value))  
                );  
            }  

            // Add the InnerException if it exists  

            if (exception.InnerException != null)  
            {  
                root.Add  
                (  
                    new ExceptionXElement  
                        (exception.InnerException, omitStackTrace)  
                );  
            }  

            return root;  
        })())  
    { }  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM