Victor Stanford
Victor Stanford

Reputation: 3

how to read the id of an xml tag with visual basic

I want to get the id of an xml tag

For example

<name id ="john">

I want to get the id that's john,

My code:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        My.Computer.Network.DownloadFile(
    "https://example.net/file.xml",
    "files/file.xml")

        Dim reader As New XmlTextReader("files/file.xml")
        While reader.Read()
            Select Case reader.NodeType
                Case XmlNodeType.Element
                    listBox1.Items.Add("<" + reader.Name & ">")
                    Exit Select
                Case XmlNodeType.Text
                    listBox1.Items.Add(reader.Value)
                    Exit Select
                Case XmlNodeType.EndElement
                    listBox1.Items.Add("")
                    Exit Select
            End Select
        End While
    End Sub
End Class

file.xml:

<?xml version="1.0"?>
<map>
  <name id="john" revision="990000237">
  <part id="3554" type="ca"/>
  <part id="3555" type="ca"/>
  </name>
  <name id="well" revision="990000236">
  <part id="3551" type="he"/>
  </name>

I don't know if there is a function for this but I was wondering if there is a way to do it, I will use WHILE to get all the ids from the tags.

Upvotes: 0

Views: 611

Answers (1)

jdweng
jdweng

Reputation: 34421

Try xml linq :

Imports System.Xml
Imports System.Xml.Linq
Module Module1

    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim map As New Map(FILENAME)
    End Sub

End Module
Public Class Map
    Public Shared maps As New List(Of Map)
    Public name As String
    Public revision As String
    Public parts As New Dictionary(Of String, String)
    Public Sub New()

    End Sub
    Public Sub New(filename As String)
        Dim doc As XDocument = XDocument.Load(filename)

        For Each xName As XElement In doc.Descendants("name")
            Dim newMap As New Map
            maps.Add(newMap)
            newMap.name = CType(xName.Attribute("id"), String)
            newMap.revision = CType(xName.Attribute("revision"), String)
            newMap.parts = xName.Descendants("part") _
                .GroupBy(Function(x) CType(x.Attribute("id"), String), Function(y) CType(y.Attribute("type"), String)) _
                .ToDictionary(Function(x) x.Key, Function(y) y.FirstOrDefault())
        Next xName

    End Sub

End Class

Upvotes: 2

Related Questions