2010-08-27 83 views
0

我希望這是一個簡單的問題!linq xml錯誤處理

在下面的代碼中一切都很好,如果元素存在,但如果沒有,它會出錯。 XDocument xmldoc = new XDocument();

 xmldoc = XDocument.Parse(response); 


     XElement errorNode = xmldoc.Root.Element("TransactionErrorCode").Element("Code"); 

我該如何測試,看看它是否存在,所以它不會出現錯誤?

回答

1

你是否得到一個NullReferenceException?看到

測試,如果你嘗試之前,它的工作存在的第一個元素:

var transactionErrorCode = xmldoc.Root.Element("TransactionErrorCode"); 
if(transactionErrorCode != null) 
{ 
    var code= transactionErrorCode .Element("Code"); 
} 
+0

感謝,但根元素僅僅是有時會出現!這導致 「對象引用未設置爲對象的實例」。 我試過是空的,但得到同樣的問題... 任何想法? – Adrian 2010-08-27 22:24:25

+0

對不起,只是閱讀並再次嘗試! 它很好用。 感謝您的幫助 – Adrian 2010-08-27 22:36:58

0
xmldoc = XDocument.Parse(response); 
if (xmlDoc != null) 
{ 
    root = xmlDoc.Root; 
    if (xmldoc.Root != null) 
    { 
    ... You get the idea 

    } 
}