2014-02-11 3 views
0

У меня есть следующие «Иерархия исключений»XElement (ы) для исключения

 Exception one = new ArithmeticException("Numbers are yucky"); 
     Exception two = new System.IO.FileNotFoundException("Files stinks", one); 
     Exception three = new ArgumentOutOfRangeException("Arguments hurt", two); 

Я пытаюсь создать ниже xml..here мой существующий код (и я понимаю, почему он не дает мне ожидаемые результаты)

 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» работать.

ответ

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

Ahhh, я был так близко. Я пропустил «XElement currentElement = root»; часть. Благодаря! – granadaCoder

Смежные вопросы