我试图从XML中获取2个值。
目前,当我运行下面的代码时,我只获得“OutTime”中的信息。我知道为什么会这样,但我不确定如何更改它以获取我想要的信息。
我想要显示的是:“人物”和“外出时间”下的所有名称。
示例:的
输出: S7-JEHILL 20:47
XML表格
<Times>
<People>
<S7-JEHILL>
<OutTime>20:47</OutTime>
</S7-JEHILL>
</People>
</Times>
当前代码
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
答案 0 :(得分:0)
首先使用XPath查询获取标记下的所有节点。然后使用ChildNodes
集合来获取a)标记名称和b)OutTime值的相关信息:
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
答案 1 :(得分:0)
将System.XML
添加到您的参考。这只是XML文件节点操作的另一种方法。
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