VB.Net XElement:循环通过 XML 的组合框的特定属性

VB.Net XElement: specific attribute from combobox looping through XML

我想要特定属性的值(例如 html 示例中的 title_1),我 select 在 visual studio 中使用组合框。我在遍历属性时遇到问题。它仅适用于 title_1 并在 title_1.

之后停止

关注我的 html-文件

<div id="main">
 <div id="title_1">
  <p>product name</p>
 </div>
 <div id="title_2">
  <p>product highlights</p>
 </div>
 <div id="content">
  <p>product price - product size - product date</p>
 </div>
</div id="main">

因此,如果我在组合框 1 中选择 title_2,我希望在我的文本框 1 中选择 产品亮点。如果我在 ComboBox1 中 select 内容,我想在我的 TextBox1 中 产品价格 - 产品尺寸 - 产品日期 。直到现在它只适用于 title_1,这里我的 TextBox1

中有 产品名称

这是我的代码

Public Class Form1

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
     Dim xelement As XElement = XElement.Load("myPATH\file.html")
     Dim attributes As IEnumerable(Of XElement) = xelement.Descendants("div")

     For Each item As XElement In attributes
        If attributes.@id = ComboBox1.Text Then
            TextBox1.Text = attributes.Value
        End If
     Next
   End Sub
End Class

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub

这可能只是一个错字。您在 attributes 中迭代每个 item,但随后您不访问 item,而是访问 attributes

For Each item As XElement In attributes
   If attributes.@id = ComboBox1.Text Then
       TextBox1.Text = attributes.Value
   End If
Next

改成这样

For Each item As XElement In attributes
    If item.@id = ComboBox1.Text Then
        TextBox1.Text = item.Value
    End If
Next

已修复。

此外,您的 html 在结束标记中包含了一个属性。那有效吗?我必须删除它才能使代码正常工作。

</div id="main">

我会添加此行以在匹配值之前清除 TextBox1,以防没有匹配项

TextBox1.Clear()

您可能将属性加载到 ComboBox 中。但是,如果您不这样做,请使用它。如果你包含它会使问题更完整

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim xelement As XElement = XElement.Load("myPATH\file.html")
    Dim attributes As IEnumerable(Of XElement) = xelement.Descendants("div")
    ComboBox1.DataSource = attributes.Select(Function(a) a.@id).ToList()
End Sub