Reputation: 483
I am trying to get 2 values out of an XML.
Currently, when I run the code below, I get just the information in "OutTime". I know why this is happening, but I am unsure how to change it to get the information I would like.
What I would like displayed is: All names under the 'People' and the 'OutTime'.
Example:
OutPut: S7-JEHILL 20:47
XML Sheet
<Times>
<People>
<S7-JEHILL>
<OutTime>20:47</OutTime>
</S7-JEHILL>
</People>
</Times>
Current Code
Dim xmlDoc As New XmlDocument()
xmlDoc.Load("C:\Users\jefhill\Desktop\TimeStamps.xml")
Dim child As XmlNode = xmlDoc.SelectSingleNode("/Times/People")
If Not (child Is Nothing) Then
Dim nr As New XmlNodeReader(child)
While nr.Read()
NameList.Items.Add(nr.Value)
End While
End If
Upvotes: 0
Views: 8744
Reputation: 56
Add System.XML
to your Reference. This is just another approach for XML file nodes manipulation.
Dim xmlDoc As New XmlDocument 'For loading xml file to read
Dim ArticleNodeList As XmlNodeList 'For getting the list of main/parent nodes
xmlDoc.Load("C:\Users\jefhill\Desktop\TimeStamps.xml") 'loading the xml file, insert your file here
ArticleNodeList = xmlDoc.GetElementsByTagName("People") 'Setting all <People> node to list
For Each articlenode As XmlNode In ArticleNodeList 'Looping through <People> node
For Each basenode As XmlNode In articlenode 'Looping all <People> childnodes
Dim result As String = ""
result = basenode.Name 'use .name to get the xml node name
For Each Node As XmlNode In basenode 'Looping all childnodes of basenode
result = result & " " & Node.InnerText 'use .Innertext to get the xml node value
Next
NameList.Items.Add(result) 'Adding Value to your variable
Next
Next
Upvotes: 2
Reputation: 19319
First use an XPath query to get all nodes under the tag. Then use the ChildNodes
collections to get the relevant information of a) the tag name and b) the OutTime value:
Sub Main()
Dim Xml As String = "<Times><People><S7-JEHILL><OutTime>20:47</OutTime></S7-JEHILL></People></Times>"
Dim Doc As New Xml.XmlDocument
Dim Xpath As String = "/Times/People"
Dim ElementList As Xml.XmlNodeList = doc.SelectNodes(xpath)
Dim PersonName, OutTime As String
'load xml to document
Doc.LoadXml(Xml)
'iterate elements in <People>
For Each Element As Xml.XmlElement In ElementList
'gets the S7-JEHILL value from the tag name
PersonName = Element.ChildNodes(0).Name
'gets the 20:47 from the tag value i.e. inner XML
OutTime = Element.ChildNodes(0).ChildNodes(0).InnerXml
Console.WriteLine(String.Format("{0} {1}", PersonName, OutTime))
Next
Console.ReadKey()
End Sub
Upvotes: 0