在循环中读取XML属性

时间:2014-03-22 12:39:50

标签: xml vb.net

我在for-next循环中读取xml属性时遇到问题,属性有数字1,2,3 如何解决?

示例xml:

<nr1>0 445 110 002</nr1> 
<make1>FIAT</make1>
<type1>CRI-1.0 </type1>
<model1>DUCATO 2.2 </model1>

<nr2>0 445 110 007</nr2>
<make2>PSA FIAT</make2>
<type2>CRI-1.0 </type2>
<model2>SCUDO 2.0JTD </model2>

<nr3>0 445 110 007</nr3>
<make3>PSA FIAT</make3>
<type3>CRI-1.0 </type3>
<model3>SCUDO 2.0JTD </model3>



1 个答案:

答案 0 :(得分:1)

您可以在元素名称上使用StartsWith

Class Car
  Public nr As String
  Public make As String
  Public type As String
  Public model As String
End Class

Sub Main()
  Dim cars = <cars>
               <nr1>0 445 110 002</nr1>
               <make1>FIAT</make1>
               <type1>CRI-1.0 </type1>
               <model1>DUCATO 2.2 </model1>

               <nr2>0 445 110 007</nr2>
               <make2>PSA FIAT</make2>
               <type2>CRI-1.0 </type2>
               <model2>SCUDO 2.0JTD </model2>

               <nr3>0 445 110 007</nr3>
               <make3>PSA FIAT</make3>
               <type3>CRI-1.0 </type3>
               <model3>SCUDO 2.0JTD </model3>
             </cars>

  Dim carsList As New List(Of Car)
  Dim newCar As New Car
  For Each el As XElement In cars.Elements
    If el.Name.ToString.StartsWith("nr") Then
      If newCar.nr IsNot Nothing Then
        carsList.Add(newCar)
        newCar = New Car
      End If
      newCar.nr = el.Value.ToString
    End If
    If el.Name.ToString.StartsWith("make") Then _
      newCar.make = el.Value.ToString
    If el.Name.ToString.StartsWith("type") Then _
      newCar.type = el.Value.ToString
    If el.Name.ToString.StartsWith("model") Then _
      newCar.model = el.Value.ToString
  Next
  carsList.Add(newCar)
End Sub

编辑:通过逗号显示一行中的所有车号。

使用LINQ:

Dim carNumbersOnly As String =
  String.Join(", ", carsList.Select(Function(car) car.nr))

没有LINQ:

Private Function CarsToString(cars As IEnumerable(Of Car)) As String
  Dim numbersList As New List(Of String)
  For Each c As Car In cars
    numbersList.Add(c.nr)
  Next
  Return String.Join(", ", numbersList)
End Function

用法:

Dim carNumbersOnly As String = CarsToString(carsList)

您可以指定TextBox.Text而不是字符串,以上内容仅供演示使用。