I am loading an object fed from an XML document that expects a string for each element whether it exists or not. Since some elements are optional this bit of code helps return an empty string instead of getting a null exception. The method loadElement below checks for null and returns string.empty instead.
See http://www.switchonthecode.com/tutorials/introduction-to-linq-simple-xml-parsing for parsing code
private List<SampleObject> readParse( string FilePath)
{
XDocument xmlDoc = XDocument.Load(FilePath);
List< SampleObject > ObjectList =
(from RANGEVARNAME in xmlDoc.Descendants("PARENTNODE")
select new SampleObject
{
item1 = loadElement(RANGEVARNAME.Element("item1")),
item2 = loadElement(RANGEVARNAME.Element("item2")),
. . .
}).ToList<SampleObject>();
lblMessage.Text = "Loading " + FilePath + " (" + ObjectList.Count + ") Records";
return (ObjectList);
}
private string loadElement(XElement E)
{
return((E==null)? string.Empty: E.Value);
}