tags:

views:

26

answers:

2

i hope this is a simple 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?

+1  A: 

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");
}
Rob Fonseca-Ensor
thanks but the root element is only there sometimes! and this results in "Object reference not set to an instance of an object."I have tried is empty but get the same problem...Any ideas?
Adrian
sorry just read and tried that again!It works great.thanks for your help
Adrian
A: 
xmldoc = XDocument.Parse(response);
if (xmlDoc != null)
{
  root = xmlDoc.Root;
  if (xmldoc.Root != null)
  {
   ... You get the idea

  }
}
Foovanadil