带有可选元素的XML可以与LINQ和匿名类型一起使用吗?

时间:2012-07-17 20:20:03

标签: xml vb.net linq

以下XML中的“CIPCode”元素是可选的:

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

我有以下代码将元素放在匿名类型中:

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

当省略CIPCode时,代码抛出异常(对象引用未设置为对象的实例。)。有没有办法配置代码,以便在适用时存储CIPCode并且不会抛出任何异常?

1 个答案:

答案 0 :(得分:2)

  

有没有办法配置代码,以便在适用时存储CIPCode并且不会抛出异常?

不确定。这很简单 - 只需使用explicit conversion to string代替:

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

当没有这样的元素时,这会给你Nothing

(请注意,文档的VB版本已损坏,因为它使用Value属性而不是......)