我有以下“异常层次结构”
Exception one = new ArithmeticException("Numbers are yucky");
Exception two = new System.IO.FileNotFoundException("Files stinks", one);
Exception three = new ArgumentOutOfRangeException("Arguments hurt", two);
我正在尝试创建下面的xml ..我现有的代码(我明白为什么它没有给我预期的结果)
XDocument returnDoc = new XDocument();
XElement root = new XElement("root");
if (null != three)
{
XElement exceptionElement = new XElement("Exception");
Exception exc = ex;
while (null != exc)
{
exceptionElement.Add(new XElement("Message", exc.Message));
exc = exc.InnerException;
}
root.Add(exceptionElement);
}
returnDoc.Add(root);
我得到这个xml:
<root>
<Exception>
<Message>Arguments hurt</Message>
<Message>Files stinks</Message>
<Message>Numbers are yucky</Message>
</Exception>
</root>
我正试图获得这个Xml ......
<root>
<Exception>
<Message>Arguments hurt</Message>
<Exception>
<Message>Files stinks</Message>
<Exception>
<Message>Numbers are yucky</Message>
</Exception>
</Exception>
</Exception>
</root>
“嵌套”异常的数量未知......可能是1到N。
我无法使用“递归XElement”来工作。
答案 0 :(得分:1)
if (null != three)
{
XElement currentElement = root;
Exception exc = three;
while (null != exc)
{
XElement exceptionElement = new XElement("Exception");
exceptionElement.Add(new XElement("Message", exc.Message));
exc = exc.InnerException;
currentElement.Add(exceptionElement);
currentElement = exceptionElement;
}
}