我想要类似的东西
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/