VB.NET中的LINQ to XML

时间:2021-04-19 19:00:23

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 don't really understand them because they're in C#, which I guess lets you do different things with LINQ(I think?).

我基本上是LINQ的新手。我在这里看了很多,我很困惑。我已经看过一些允许我使用LINQ的强类型对象的例子,但是我不太了解它们,因为它们在C#中,我想让你用LINQ做不同的事情(我想?)。

Anyways, this is what I'm trying to do:

无论如何,这就是我想要做的:

Dim productXML As XDocument = XDocument.Load( _
    Server.MapPath("~/App_Data/products.xml"))

Dim products As List(Of Product) = 'some query to select all products ?'

'set up Product properties here'
someProduct.ProductID = 'somehow get productid from XML'

EDIT - I just want to get a list of all the products from the XML doc and put them into a Generics list.

编辑 - 我只想获取XML文档中所有产品的列表,并将它们放入泛型列表中。

4 个解决方案

#1


11  

Marc is right, VB lets you do lots of nice stuff. I'm a C# guy myself, but I just knocked up a VB solution to see how to do it for you. I've posted the code below and explained the key parts. I was very impressed with the features VB has for Xml!

Marc是对的,VB可以让你做很多好事。我自己就是C#家伙,但我刚刚敲了VB解决方案,看看如何为你做这件事。我已经发布了下面的代码并解释了关键部分。 VB对Xml的功能给我留下了深刻的印象!

I see in your code sample that you've already managed to load your Xml into an XDocument. Once you've done your XDocument.Load you can access the Xml document using some special syntax.

我在您的代码示例中看到您已经设法将Xml加载到XDocument中。完成XDocument.Load后,您可以使用一些特殊语法访问Xml文档。

For starters we want to get all the products from the document; i.e. all < Product > elements. We need to do the following:

对于初学者,我们希望从文档中获取所有产品;即所有 元素。我们需要做以下事情:

Dim products = productsDoc...<Product>

This says that you want all < Product > elements from the document. This gives us an IEnumerable collection of XElements.

这表示您需要文档中的所有 元素。这为我们提供了一个IEnumerable XElements集合。

Once we've pulled an individual product from the collection we'll want to access the product's values like it's name or price. To do that we need to do the following:

一旦我们从集合中提取单个产品,我们就会想要访问产品的价值,例如它的名称或价格。为此,我们需要执行以下操作:

' this gets the value of the price element within a product
product.<Price>.Value

Here's a full example along with the expected output for you to look at:

这是一个完整的示例以及您要查看的预期输出:

Module Module1

    ' some products xml to use for this example
    Dim productsXml = <Xml>
                          <Product>
                              <Name>Mountain Bike</Name>
                              <Price>59.99</Price>
                          </Product>
                          <Product>
                              <Name>Arsenal Football</Name>
                              <Price>9.99</Price>
                          </Product>
                          <Product>
                              <Name>Formula One Cap</Name>
                              <Price>14.99</Price>
                          </Product>
                          <Product>
                              <Name>Robin Hood Bow</Name>
                              <Price>8.99</Price>
                          </Product>
                      </Xml>

    Sub Main()

        ' load the xml into an XDocument
        ' NOTE: this line isn't needed when using inline XML as per this example, 
        ' but I wanted to make this code easy to modify for reading in text files
        Dim productsDoc = System.Xml.Linq.XDocument.Parse(productsXml.ToString())

        ' get all <Product> elements from the XDocument
        Dim products = From product In productsDoc...<Product> _
                       Select product

        ' go through each product
        For Each product In products
            ' output the value of the <Name> element within product
            Console.WriteLine("Product name is {0}", product.<Name>.Value)
            ' output the value of the <Price> element within product
            Console.WriteLine("Product price is {0}", product.<Price>.Value)
        Next

    End Sub

End Module

Program output is:

程序输出是:

Product name is Mountain Bike
Product price is 59.99
Product name is Arsenal Football
Product price is 9.99
Product name is Formula One Cap
Product price is 14.99
Product name is Robin Hood Bow
Product price is 8.99

I hope this has been helpful. If you'd like any more information please just ask :-)

希望这有用。如果您想了解更多信息,请询问:-)

It's hard to write something coherent at bedtime! :-)

睡前很难写出连贯的东西! :-)

#2


2  

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 = _
    <Xml>
        <Product>
            <Name>Mountain Bike</Name>
            <Price>59.99</Price>
        </Product>
        <Product>
            <Name>Arsenal Football</Name>
            <Price>9.99</Price>
        </Product>
        <Product>
            <Name>Formula One Cap</Name>
            <Price>14.99</Price>
        </Product>
        <Product>
            <Name>Robin Hood Bow</Name>
            <Price>8.99</Price>
        </Product>
    </Xml>

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...<Product> _
                   Select New Product With {.Name = prod.<Name>.Value, .Price = prod.<Price>.Value}

    ' go through each product '
    For Each prod In products
        ' output the value of the <Name> element within product '
        Console.WriteLine("Product name is {0}", prod.Name)
        ' output the value of the <Price> element within product '
        Console.WriteLine("Product price is {0}", prod.Price)
    Next

End Sub

End Module

#3


0  

OK, how about this?

好的,这个怎么样?

Dim productXML As XDocument = XDocument.Load( _    
    Server.MapPath("~/App_Data/products.xml"))    
'
For Each product as Product In productXML.Document.Elements("Product")
    'do something with each product
Next

#4


0  

I may be a little late to the party here, but I can't believe nobody has offered the XmlSerializer option:

我在这里可能会迟到一点,但我不相信没有人提供XmlSerializer选项:

Public Class Product
    Property Description As String
    Property Price As Double

    Public Shared Function FromXml(serverPath As String) As IEnumerable(Of Product)

       Using fs = IO.File.OpenRead(serverPath)
           Dim p As New Product
           Return New XmlSerializer(p.GetType).Deserialize(fs)
       End Using

    End Function

End Class

You can then return an iEnumerable of Product from the shared function:

然后,您可以从共享函数返回iEnumerable of Product:

dim listOfProducts = Product.FromXml(Server.MapPath("~/App_Data/products.xml"))

This doesn't use LinqToXml as such, but it deserializes the xml to an iEnumerable of product, which you can use Linq on as usual.

这不会使用LinqToXml,但它会将xml反序列化为iEnumerable产品,您可以像往常一样使用Linq。

#1


11  

Marc is right, VB lets you do lots of nice stuff. I'm a C# guy myself, but I just knocked up a VB solution to see how to do it for you. I've posted the code below and explained the key parts. I was very impressed with the features VB has for Xml!

Marc是对的,VB可以让你做很多好事。我自己就是C#家伙,但我刚刚敲了VB解决方案,看看如何为你做这件事。我已经发布了下面的代码并解释了关键部分。 VB对Xml的功能给我留下了深刻的印象!

I see in your code sample that you've already managed to load your Xml into an XDocument. Once you've done your XDocument.Load you can access the Xml document using some special syntax.

我在您的代码示例中看到您已经设法将Xml加载到XDocument中。完成XDocument.Load后,您可以使用一些特殊语法访问Xml文档。

For starters we want to get all the products from the document; i.e. all < Product > elements. We need to do the following:

对于初学者,我们希望从文档中获取所有产品;即所有 元素。我们需要做以下事情:

Dim products = productsDoc...<Product>

This says that you want all < Product > elements from the document. This gives us an IEnumerable collection of XElements.

这表示您需要文档中的所有 元素。这为我们提供了一个IEnumerable XElements集合。

Once we've pulled an individual product from the collection we'll want to access the product's values like it's name or price. To do that we need to do the following:

一旦我们从集合中提取单个产品,我们就会想要访问产品的价值,例如它的名称或价格。为此,我们需要执行以下操作:

' this gets the value of the price element within a product
product.<Price>.Value

Here's a full example along with the expected output for you to look at:

这是一个完整的示例以及您要查看的预期输出:

Module Module1

    ' some products xml to use for this example
    Dim productsXml = <Xml>
                          <Product>
                              <Name>Mountain Bike</Name>
                              <Price>59.99</Price>
                          </Product>
                          <Product>
                              <Name>Arsenal Football</Name>
                              <Price>9.99</Price>
                          </Product>
                          <Product>
                              <Name>Formula One Cap</Name>
                              <Price>14.99</Price>
                          </Product>
                          <Product>
                              <Name>Robin Hood Bow</Name>
                              <Price>8.99</Price>
                          </Product>
                      </Xml>

    Sub Main()

        ' load the xml into an XDocument
        ' NOTE: this line isn't needed when using inline XML as per this example, 
        ' but I wanted to make this code easy to modify for reading in text files
        Dim productsDoc = System.Xml.Linq.XDocument.Parse(productsXml.ToString())

        ' get all <Product> elements from the XDocument
        Dim products = From product In productsDoc...<Product> _
                       Select product

        ' go through each product
        For Each product In products
            ' output the value of the <Name> element within product
            Console.WriteLine("Product name is {0}", product.<Name>.Value)
            ' output the value of the <Price> element within product
            Console.WriteLine("Product price is {0}", product.<Price>.Value)
        Next

    End Sub

End Module

Program output is:

程序输出是:

Product name is Mountain Bike
Product price is 59.99
Product name is Arsenal Football
Product price is 9.99
Product name is Formula One Cap
Product price is 14.99
Product name is Robin Hood Bow
Product price is 8.99

I hope this has been helpful. If you'd like any more information please just ask :-)

希望这有用。如果您想了解更多信息,请询问:-)

It's hard to write something coherent at bedtime! :-)

睡前很难写出连贯的东西! :-)

#2


2  

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 = _
    <Xml>
        <Product>
            <Name>Mountain Bike</Name>
            <Price>59.99</Price>
        </Product>
        <Product>
            <Name>Arsenal Football</Name>
            <Price>9.99</Price>
        </Product>
        <Product>
            <Name>Formula One Cap</Name>
            <Price>14.99</Price>
        </Product>
        <Product>
            <Name>Robin Hood Bow</Name>
            <Price>8.99</Price>
        </Product>
    </Xml>

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...<Product> _
                   Select New Product With {.Name = prod.<Name>.Value, .Price = prod.<Price>.Value}

    ' go through each product '
    For Each prod In products
        ' output the value of the <Name> element within product '
        Console.WriteLine("Product name is {0}", prod.Name)
        ' output the value of the <Price> element within product '
        Console.WriteLine("Product price is {0}", prod.Price)
    Next

End Sub

End Module

#3


0  

OK, how about this?

好的,这个怎么样?

Dim productXML As XDocument = XDocument.Load( _    
    Server.MapPath("~/App_Data/products.xml"))    
'
For Each product as Product In productXML.Document.Elements("Product")
    'do something with each product
Next

#4


0  

I may be a little late to the party here, but I can't believe nobody has offered the XmlSerializer option:

我在这里可能会迟到一点,但我不相信没有人提供XmlSerializer选项:

Public Class Product
    Property Description As String
    Property Price As Double

    Public Shared Function FromXml(serverPath As String) As IEnumerable(Of Product)

       Using fs = IO.File.OpenRead(serverPath)
           Dim p As New Product
           Return New XmlSerializer(p.GetType).Deserialize(fs)
       End Using

    End Function

End Class

You can then return an iEnumerable of Product from the shared function:

然后,您可以从共享函数返回iEnumerable of Product:

dim listOfProducts = Product.FromXml(Server.MapPath("~/App_Data/products.xml"))

This doesn't use LinqToXml as such, but it deserializes the xml to an iEnumerable of product, which you can use Linq on as usual.

这不会使用LinqToXml,但它会将xml反序列化为iEnumerable产品,您可以像往常一样使用Linq。