[英]Parse XML elements into List(Of String) with VB.NET
我有一個巨大的XML文件從Web服務調用返回,我正在解析它。 我遇到的一個問題是將多個元素(具有相同的名稱)解析為List(Of String)。 XML看起來像這樣
<BasicPropertyInfo ChainCode="CY" GEOConfidenceLevel="3" HotelCityCode="KWI" HotelCode="0048191" HotelName="COURTYARD KUWAIT CITY MARRIOTT" Latitude="29.377052" Longitude="47.990384" NumFloors="21" RPH="001">
<Address>
<AddressLine>AL SHUHADA ST PO BOX 1216 DASM</AddressLine>
<AddressLine>DASMAN KUWAIT CITY KW 15463</AddressLine>
<CountryCode>KW</CountryCode>
</Address>
<Award Provider="NTM3 CROWN" />
<ContactNumbers>
<ContactNumber Phone="965-22997000" Fax="965-22997001" />
</ContactNumbers>
我的課很簡單
Namespace Classes.Models
Public Class PropertyInfo
Public Property ChainCode() As String
Public Property HotelCityCode() As String
Public Property HotelCode() As String
Public Property HotelName() As String
Public Property Address() As IEnumerable(Of String)
Public Property PhoneNumber() As String
Public Property FaxNumber() As String
End Class
End Namespace
在下面的代碼中,如果我刪除我正在嘗試獲取AddressLine的地方,它會填充該類,只要我添加代碼就會彈出錯誤
無法將類型為'd__14
2[System.Xml.Linq.XElement,System.Char]' to type 'System.Collections.Generic.IEnumerable
對象強制2[System.Xml.Linq.XElement,System.Char]' to type 'System.Collections.Generic.IEnumerable
1 [System.String]'。
Public Function ParsePropertyInfo() As IEnumerable(Of PropertyInfo)
Try
Dim ns As XNamespace = "http://webservices.sabre.com/sabreXML/2003/07"
Dim prop As PropertyInfo
For Each n As XElement In _xDoc.Descendants(ns + "BasicPropertyInfo")
_properties.Add(New PropertyInfo With { _
.ChainCode = n.Attribute("ChainCode").Value, _
.HotelCityCode = n.Attribute("HotelCityCode").Value, _
.HotelCode = n.Attribute("HotelCode").Value, _
.HotelName = n.Attribute("HotelName").Value,
.PhoneNumber = n.Element(ns + "ContactNumbers").Element(ns + "ContactNumber").Attribute("Phone").Value, _
.Address = n.Descendants(ns + "AddressLine").SelectMany(Function(el As String) el), _
.FaxNumber = n.Element(ns + "ContactNumbers").Element(ns + "ContactNumber").Attribute("Fax").Value})
Next
Return _properties
Catch ex As Exception
ErrorMessage = ex.Message
Return Nothing
End Try
End Function
那么我如何將AddressLine元素放入我的通用列表中呢?
使用Select
而不是SelectMany
:
.Address = n.Descendants(ns + "AddressLine").Select(Function(el As String) el)
SelectMany
查看您的IEnumerable(Of XElement)
,將每個XElement
轉換為string
,然后將這些字符串中的所有字符合並為一個巨大的char
集合。 那是因為string
實現了IEnumerable(Of char)
。
並且您應該在Select
之后添加ToList()
調用,以確保您只存儲一個string
實例的集合,而不是每次訪問該屬性時將執行的查詢定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.