VB.NET XML parser loop
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 开发者_C百科an error after the first go around. I must be missing something?
David
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.
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.
精彩评论