Can XML with optional elements be used with LINQ and Anonymous Types?

enrorrysheesk

New Member
The "CIPCode" element in the following XML is optional:\[code\]<?xml version="1.0" encoding="utf-8"?><StateCodesList SchoolYear="2012-2013" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="CourseCodesList.xsd"> <Year>2013</Year> <Course> <StateCode>990001</StateCode> <Description>Reading</Description> <ShortName>Reading</ShortName> <LongName>Reading</LongName> <CIPCode>1.01</CIPCode> <Type>99</Type> </Course> <Course> <StateCode>9902</StateCode> <Description>Math</Description> <ShortName>Short</ShortName> <LongName>Long</LongName> <Type>70</Type> </Course></StateCodesList>\[/code\]I have the following code which puts the elements in an Anonymous Type:\[code\]Using aStreamReader As New StreamReader(New MemoryStream(criteria.File)) 'File is the XML in Byte() form Dim xDoc As System.Xml.Linq.XDocument xDoc = System.Xml.Linq.XDocument.Load(aStreamReader) '....do some non-relevant stuff here Dim courses = From myCourse In xDoc.Descendants("Course") Select New With { .StateCode = myCourse.Element("StateCode").Value, _ .Description = myCourse.Element("Description").Value, _ .ShortName = myCourse.Element("ShortName").Value, _ .LongName = myCourse.Element("LongName").Value, _ .Type = myCourse.Element("Type").Value, _ .CipCode = myCourse.Element("CIPCode").Value _ } '....do some non-relevant stuff hereEnd Using\[/code\]The code throws an exception (Object reference not set to an instance of an object.) when CIPCode is left out. Is there a way to configure the code so that CIPCode is stored when applicable and no exception get thrown?
 
Back
Top