Reputation: 77
I have a XML file with data about servers in it. The country and the IP of the server.
<?xml version="1.0"?>
<servers>
<server>
<location>Belgium</location>
<ip>192.168.0.1</ip>
</server>
<server>
<location>The Netherlands</location>
<ip>127.0.0.6</ip>
</server>
</servers>
I want to add the location name + IP + ping to the IP in one line in the listbox and so on for every server.
This is my code so far but it only tells me the location. I have no idea how to append the IP and ping to the IP.
Dim xr As XmlReader = XmlReader.Create("http://127.0.0.1/servers.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "location" Then
lsbServers.Items.Add(xr.ReadElementString)
Else
xr.Read()
End If
Loop
How do I add the IP and ping to the IP to the location in the listbox?
Upvotes: 1
Views: 1147
Reputation: 43743
The XmlReader
class is useful for some tasks, but, by design, it only inspects one node at a time. In a case like this, where you need to access multiple elements at once in a random-access fashion, it would be easier to use either the XmlDocument
or XDocument
class. For instance:
Dim doc As New XmlDocument()
doc.Load("http://127.0.0.1/servers.xml")
For Each serverNode As XmlNode In doc.SelectNodes("/servers/server")
Dim location As String = serverNode.SelectSingleNode("location").InnerText
Dim ip As String = serverNode.SelectSingleNode("ip").InnerText
Next
Or,
Dim doc As XDocument = XDocument.Load("http://127.0.0.1/servers.xml")
For Each serverElement As XElement In doc.<servers>.<server>
Dim location As String = serverElement.<location>.Value
Dim ip As String = serverElement.<ip>.Value
Next
Then, when you add the item to the list box, you can concatenate the data into a string and/or format it however you like, for instance:
lsbServers.Items.Add(location & " - " & ip))
Or:
lsbServers.Items.Add(String.Format("{0} ({1})", location, ip))
However, when you have multiple data per item in the list, you may want to consider using a control which supports showing multiple columns of data, such as the ListView
or DataGrid
controls. (In order to show columns in the ListView
control, you need to set the View
property to Details
).
Upvotes: 3
Reputation: 125650
I would use LINQ to XML:
Dim xr As XmlReader = XmlReader.Create("http://127.0.0.1/servers.xml")
Dim xDoc As XDocument = XDocument.Load(xr)
For Each server as XElement In xDoc.Root.Elements("server")
Dim location As String = CType(server.Element("location"), String)
Dim ip As String = CType(server.Element("ip"), String)
' your ping logic goes here '
Dim ping as String = GetPing(ip)
lsbServers.Items.Add(String.Format("{0} - {1} - {2}", location, ip, ping))
Next
Upvotes: 1