1

I am trying to get value from Xml file using xpath. Here is my code:

XElement docQuote = XElement.Parse(Financial);
string result= docQuote.XPathSelectElement("//ns:Quote",nsmgr).ToString(SaveOptions.DisableFormatting);

This is working fine when Quote Xml node exist in XML file and return value in between Quote tags. However Quote xml tag not exist in the XMl file it generates and exception.

Object reference not set to an instance of an object.

I have tried to check NULL as below:

if(docQuote.XPathSelectElement("//ns:Quote",nsmgr) != null)

and

if(docQuote.XPathSelectElement("//ns:Quote",nsmgr) != null).value != null)

However it doesn't avoid the execution when null.

Please help me to avoid execution when Xml tag not exist.

devan
  • 1,643
  • 8
  • 37
  • 62

2 Answers2

2

Maybe the boolean() XPATH function helps here:

boolean(//*[name()='Quote'])

If element Quote exists, boolean(//*[name()='Quote']) should return true, otherwise false.

XElement docQuote = XElement.Parse(Financial);
string result= docQuote.XPathSelectElement("boolean(//*[name()='Quote'])",nsmgr).ToString(SaveOptions.DisableFormatting);
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Stefan Gentz
  • 417
  • 4
  • 7
-1

Try

 XElement docQuote = XElement.Parse(Financial);
   if(docQuote != null && docQuote.XPathSelectElement("//ns:Quote",nsmgr) != null)
   {
    string result=   docQuote.XPathSelectElement("//ns:Quote",nsmgr).ToString(SaveOptions.DisableFormatting);
   }
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93
  • This will not work since docQuote is not null. and when going to execute second half your check it fire the exception. – devan Dec 11 '12 at 10:06
  • Can you show the full code. nsmgr Financial object e.t.c May be there is error in declaration Check http://stackoverflow.com/questions/5819305/xpathselectelement-always-returns-null P.S. [Voted -1 :)] – Kamran Shahid Dec 11 '12 at 10:36