What is the best way to recover from missing nodes?
I am filling up a user interface with many fields. The fields are filled by searhing each XML element value like this:
txtCreDtTm.Text = GrpHdr.Element(ns + "CreDtTm").Value;
These lines are as many as fields in the screen, say 40. If one of the elements are missing in the xml table, then the field should just be left empty. But in such a case I will get also an exeption for not found element.
Is the only way to recover from missing element by surrounding each of the lines with try/catch, or test each of the elemnts before attemting to assign them? Or is there a way similar to put one try around all, and after catch continue from the next line? The following of course skips the rest after the exception caused by missing element.
XDocument cpo = XDocument.Load(filename);
XElement po = cpo.Root.Element(ns +"pain.001.001.02");
// LINQ to XML query
try
{
XElement GrpHdr = po.Element(ns + "GrpHdr");
txtMsgId.Text = GrpHdr.Element(ns + "MsgId").Value;
txtCreDtTm.Text = GrpHdr.Element(ns + "CreDtTm").Value;
cboBtchBookg.Text = GrpHdr.Element(ns + "BtchBookg").Value;
lblNbOfTxs.Text = GrpHdr.Element(ns + "NbOfTxs").Value;
lblCtrlSum.Text = GrpHdr.Element(ns + "CtrlSum").Value;
cboGrpg.Text = GrpHdr.Element(ns + "Grpg").Value;
txtNm.Text = GrpHdr.Element(ns + "InitgPty").Element(ns + "Nm").Value;
txtBkPtyId.Text = GrpHdr.Element(ns + "InitgPty").Element(ns + "BkPtyId").Value;
txtAdrLine11.Text = GrpHdr.Element(ns + "InitgPty").Element(ns + "PstlAdr").Element(ns + "AdrLine").Value;
...
}
/petri