LINQ to XML in VB.NET

前端 未结 4 1527
南方客
南方客 2020-12-10 06:07

I\'m basically brand new to LINQ. I\'ve looked around a lot on here and am pretty confused. I\'ve seen some examples that allow me to strong type objects using LINQ but I do

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 06:41

    Doctor Jones posted an excellent example!

    To get a collection of named type objects as opposed to anonymous type objects (both are strongly typed) do this:

    Module Module1
    
    ' some products xml to use for this example '
        Dim productsXml As XElement = _
        
            
                Mountain Bike
                59.99
            
            
                Arsenal Football
                9.99
            
            
                Formula One Cap
                14.99
            
            
                Robin Hood Bow
                8.99
            
        
    
    Class Product
    
        Private _name As String
        Public Property Name() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property
    
        Private _price As Double
        Public Property Price() As Double
            Get
                Return _price
            End Get
            Set(ByVal value As Double)
                _price = value
            End Set
        End Property
    
    End Class
    
    Sub Main()
    
        ' get an IEnumerable of Product objects '
        Dim products = From prod In productsXml... _
                       Select New Product With {.Name = prod..Value, .Price = prod..Value}
    
        ' go through each product '
        For Each prod In products
            ' output the value of the  element within product '
            Console.WriteLine("Product name is {0}", prod.Name)
            ' output the value of the  element within product '
            Console.WriteLine("Product price is {0}", prod.Price)
        Next
    
    End Sub
    
    End Module
    

提交回复
热议问题