【发布时间】:2014-02-09 08:15:12
【问题描述】:
我正在尝试使用 LINQ To XML 解析来自 Web 服务的 XML 提要(我的第一次尝试,请多多包涵)。我有以下函数,它应该从 XML 中创建一个 IEnumerable(Of RoomRate)
Public Function ParseRates() As IEnumerable(Of RoomRate)
Try
Return From el As XElement In _xDoc...<RoomRate>
Select New RoomRate With { _
.GuaranteeSurchargeRequired = el.@GuaranteeSurchargeRequired, _
.IATACharacteristicIdentification = el.@IATACharacteristicIdentification, _
.IATAProductIdentification = el.@IATAProductIdentification, _
.RPH = el.@RPH, _
.CancellationPolicy = el...<AdditionalInfo>...<CancellationPolicy>.@Numeric, _
.Commission = el...<AdditionalInfo>...<Commission>.@NonCommission, _
.Rate = el...<Rates>...<Rate>.@Amount, _
.CurrencyCode = el...<Rates>...<Rate>.@CurrencyCode, _
.TotalPrice = el...<Rates>...<Rate>...<HotelTotalPricing>.@Amount, _
.Surcharge = el...<Rates>...<Rate>...<TotalSurchjarges>.@Amount}
Catch ex As Exception
ErrorMessage = ex.Message
Return Nothing
End Try
End Function
我正在这样测试它
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim parse As New ParseSabre(Server.MapPath("~/XML/SabreSample.xml"))
Dim rates As IEnumerable(Of RoomRate)()
rates = parse.ParseRates()
'If rates = Nothing Then
'End If
For Each rate As RoomRate In rates
Response.Write(rate.GuaranteeSurchargeRequired)
Response.Write(rate.IATACharacteristicIdentification)
Response.Write(rate.IATAProductIdentification)
Response.Write(rate.RPH)
Response.Write(rate.CancellationPolicy)
Response.Write(rate.Commission)
Response.Write(rate.Rate)
Response.Write(rate.CurrencyCode)
Response.Write(rate.TotalPrice)
Response.Write(rate.Surcharge)
Response.Write(vbNewLine)
Next
End Sub
但是在这一行
rates = parse.ParseRates()
我收到此错误:
无法转换类型的对象 'WhereSelectEnumerableIterator
2[System.Xml.Linq.XElement,Lodgx.Classes.Models.RoomRate]' to type 'System.Collections.Generic.IEnumerable1[Lodgx.Classes.Models.RoomRate][]'.
谁能帮我弄清楚我哪里出了问题?
编辑
我已经把我的代码改成了这个,这样更好吗? (另外,这段代码仍然出现同样的错误)
_rates = _xDoc.Descendants("RoomRate").Select(Function(n) New RoomRate With { _
.GuaranteeSurchargeRequired = n.Attribute("GuarateeSurchargeRequired").Value, _
.IATACharacteristicIdentification = n.Attribute("IATACharacteristicIdentification").Value, _
.IATAProductIdentification = n.Attribute("IATAProductIdentification").Value,
.RPH = n.Attribute("RPH").Value})
【问题讨论】:
-
正是我在对您上一个问题的评论中写的。如果使用简单的老式代码(无 LINQ),则可以轻松避免此类问题。请用它重写,发现问题(现在很有意义) - 解决了。
-
请注意,除非您发表评论并通过
@符号引用我,否则我不会收到有关您的更改的通知。关于您的编辑,.Select也是 LINQ,请改写为旧式代码行,即每行一个作业。然后,您的 VS 将在有问题的线路上爆炸,并出现有意义的错误。Dim rr As New RoomRate:rr.GuaranteeSurchargeRequired = n.Attribute("GuarateeSurchargeRequired").Value等等。
标签: vb.net linq-to-xml