开发者

linq xml error handling

开发者 https://www.devze.com 2023-01-13 04:55 出处:网络
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.

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

精彩评论

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