2014-02-11 47 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

啊,我太親近了。我錯過了「XElement currentElement = root」部分。謝謝! – granadaCoder