开发者

linq xml error handling

i hope this is a si开发者_JAVA百科mple question!

in the following code all is well if the element exists but if not it errors out. XDocument xmldoc = new XDocument();

        xmldoc = XDocument.Parse(response);


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

How can i test to see if it exists so it doesnt trow an error?


Were you getting a NullReferenceException?

Test to see if the first element exists before you try to work with it:

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


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

  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜