tags:

views:

109

answers:

2

Hey all i am new to XML parsing on VB.net. This is the code i am using to parse an XML file i have:

Dim output As StringBuilder = New StringBuilder()

Dim xmlString As String = _
    "<ip_list>" & _
        "<ip>" & _
            "<ip>192.168.1.1</ip>" & _
            "<ping>9 ms</ping>" & _
            "<hostname>N/A</hostname>" & _
         "</ip>" & _
         "<ip>" & _
             "<ip>192.168.1.6</ip>" & _
             "<ping>0 ms</ping>" & _
             "<hostname>N/A</hostname>" & _
         "</ip>" & _
   "</ip_list>"

Using reader As XmlReader = XmlReader.Create(New StringReader(xmlString))
        'reader.ReadStartElement("ip_list")

        Do Until reader.EOF
            reader.ReadStartElement("ip_list")
            reader.ReadStartElement("ip")
            reader.ReadStartElement("ip")
            reader.MoveToFirstAttribute()

            Dim theIP As String = reader.Value.ToString
            reader.ReadToFollowing("ping")
            Dim thePing As String = reader.ReadElementContentAsString().ToString
            reader.ReadToFollowing("hostname")
            Dim theHN As String = reader.ReadElementContentAsString().ToString

            MsgBox(theIP & " " & thePing & " " & theHN)
            reader.ReadEndElement()
        Loop

        reader.Close()
    End Using

I put the do until reader.EOF myself but it does not seem to work. It keeps giving an error after the first go around. I must be missing something?

David

+1  A: 

You never closed the first <ip> element.
Therefore, when the loop repeats, it tries to read a second <ip> inside the first one.

You need to call ReadEndElement() twice at the end of the loop.

SLaks
Thanks for the comment. I added those twice at the end but it seems to not loop around again (only does it once)
StealthRT
Try calling it only once.
SLaks
Yeah, tried that as well and it still only shows one instead of 2. Gives the same error as before.
StealthRT
Updated the code as well to reflect your suggestion.
StealthRT
Move `reader.ReadStartElement("ip_list")` outside the loop. (Since there is only one `<ip_list>` element)
SLaks
Did that as well (notice i commented it out in the code above). Still the same issue though. It loops twice but on the 2nd it stops that the first "ip" with an error.
StealthRT
What error do you get?
SLaks
Sorry, there is no error BUT it does only loop once when using the ip_list outside the loop.
StealthRT
A: 

If you are able to use .NET 3.5, I would recommend using the XML literals and LINQ syntax.

Dim ips = From xe In XElement.Parse(xmlString).<ip> _
          Select New With {.IP = xe.<ip>.Value, _
                           .Ping = xe.<ping>.Value, _
                           .HostName = xe.<hostname>.Value}
'if you only want one
Dim firstIp = ips.First()

There's also an XElement.Load you can use to load from a file.

Gideon Engelberth