2014-02-11 48 views
0

我有一个巨大的XML文件正在从Web服务调用返回,并且正在解析它。我遇到的一个问题是将多个元素(具有相同的名称)解析为List(Of String)。该XML看起来像这样使用VB.NET将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 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元素融入到我的泛型列表?

回答

2

使用Select代替SelectMany

.Address = n.Descendants(ns + "AddressLine").Select(Function(el As String) el) 

SelectMany看你IEnumerable(Of XElement),将每个XElementstring,然后合并从这些字符串中的所有字符之一,char巨大集合。这是因为string执行IEnumerable(Of char)

你应该Select后可能增加ToList()通话,以确保您只储存string实例,而不是一个查询定义,这将是你每次访问该属性时所执行的集合。

+0

谢谢@MarcinJuraszec这样做! – PsychoCoder