I’m trying to iterate through a simple XML file and display the data in a ListBox as two fields. I have full control over the XML file, so I can change the format to make it easier.
Here’s my example XML, stored in an EditField called parse_InputText
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<League>
<Player>
<name>Kyle</name>
<position>2B</position>
</Player>
<Player>
<name>Mike</name>
<position>1B</position>
</Player>
<Player>
<name>Tom</name>
<position>1A</position>
</Player>
<Player>
<name>Bret</name>
<position>1C</position>
</Player>
</League>
Here’s my code to populate Player name in a listbox (ListBox1) when the XML data is store in an EditField (bodyFld). This works perfectly:
dim xml as new XMLDocument(bodyFld.text)
dim nodeList as XmlNodeList
dim root As XmlNode
dim node As XmlNode
dim i as integer
root = xml.DocumentElement
nodeList = xml.Xql("//Player")
If root.ChildCount > 0 Then
For i = 0 To nodeList.Length - 1
node = nodeList.Item(i)
ListBox1.AddRow(node.GetAttribute("name"))
Next
End if
In my real use case though, I’ll likely have a few sentences in place of the Player names. In that case, I think using a value would be a better use than applying an attribute. So with that challenge, I updated the XML above to this format:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<League>
<Player>
<name>Kyle</name>
<position>2B</position>
</Player>
<Player>
<name>Mike</name>
<position>1B</position>
</Player>
<Player>
<name>Tom</name>
<position>1A</position>
</Player>
<Player>
<name>Bret</name>
<position>1C</position>
</Player>
</League>
Now, I’m attempting to iterate through the XML file and grab the value. I modified my code with an additional For loop, but running this code crashes.
dim xml as new XMLDocument(bodyFld.text)
dim nodeList as XmlNodeList
dim root As XmlNode
dim node, node1 As XmlNode
dim i, n, count as integer
dim out as string
root = xml.DocumentElement
nodeList = xml.Xql("//Player") // Find all Player Info
If root.ChildCount > 0 Then
For i = 0 To nodeList.Length - 1
node = nodeList.Item(i)
count = node.ChildCount
For n = 0 to count - 1
node1 = xml.DocumentElement.Child(n)
ListBox1.AddRow(node.FirstChild.FirstChild.Value)
next
Next
End if
Is there anything I’m missing?