Reputation: 1653
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.
Upvotes: 1
Views: 1579
Reputation: 419
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);
Upvotes: 2
Reputation: 4124
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);
}
Upvotes: -1