ray
ray

Reputation: 8699

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

The "CIPCode" element in the following XML is optional:

<?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>

I have the following code which puts the elements in an Anonymous Type:

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 here
End Using

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?

Upvotes: 1

Views: 178

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500595

Is there a way to configure the code so that CIPCode is stored when applicable and no exception get thrown?

Sure. It's really easy - just use the explicit conversion to string instead:

.CipCode = CType(myCourse.Element("CIPCode"), String)

That will give you Nothing when there's no such element.

(Note that the VB version of the docs is broken, as it uses the Value property instead...)

Upvotes: 2

Related Questions