2010-08-27 87 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 

    } 
}