Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to handle selectsinglenode parse error 1

Status
Not open for further replies.

AndyH1

Programmer
Jan 11, 2004
350
GB
I am trying to parse on an xmlDoc to find all the companies with a specific postcode, or find out if there are none with that postcode. Ive written the code below which parses out all the companies with the postcode which works fine.

My problem is the situation where there are no companies that match the postcode. In this case, as I understand resultDoc is empty, I detect this as it throws a nullReference exception. This works, but I don't feel its very elegant to use exception catching to do this, and wondered if anyone could suggest a better way covering this. Or is this the only way to do this?

try
{
resultDoc.LoadXml(resultDoc.SelectSingleNode("descendant::company[address/postcode='" + postcode.Text + "']").OuterXml);
// POSTCODE Filter
if (resultDoc.SelectNodes("//company").Count == 1)
{
// narrowed it down to 1 so use
createRegistration(email.Text, resultDoc.SelectSingleNode("//companyID").InnerText);
);
} catch
{
// no record with postcode has not been found
}
 
why are you loading the single node into the resultDoc? Just use the result.
Code:
var query = string.Format("descendant::company[address/postcode='{0}']", postcode.Text);
var node = resultDoc.SelectSingleNode(query);
if(node != null)
{
   var companyId = node.SelectSingleNode("//companyID").InnerText;
   createRegistration(email.Text, companyId);
}
else
{
  //do something with the null value.
}
you may event be able to reduce the code with a different query
Code:
var query = string.Format("descendant::company[address/postcode='{0}']/companyID", postcode.Text);
var companyId = resultDoc.SelectSingleNode(query);
if(companyId != null)
{
   createRegistration(email.Text, companyId.InnerText);
}
else
{
  //do something with the null value.
}

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Thanks jason,

Looks a lot neater and more efficent,

AndyH1
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top