带有可选元素的XML可以与LINQ和匿名类型一起使用吗? [英] Can XML with optional elements be used with LINQ and Anonymous Types?
问题描述
以下XML中的"CIPCode"元素是可选的:
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
当忽略CIPCode时,代码将引发异常(对象引用未设置为对象的实例.).有没有一种方法可以配置代码,以便在适用时存储CIPCode并且不会引发异常?
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?
推荐答案
有没有一种配置代码的方式,以便在适用时存储CIPCode并且不会引发异常?
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)
在没有这样的元素时,它将为您提供Nothing
.
That will give you Nothing
when there's no such element.
(请注意,文档的VB版本已损坏,因为它改用了Value
属性...)
(Note that the VB version of the docs is broken, as it uses the Value
property instead...)
这篇关于带有可选元素的XML可以与LINQ和匿名类型一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!