2016-06-22 8 views
0

Ich versuche, 2 Werte aus einem XML zu erhalten.Lesen eines Eltern- und Kindknoten aus xml

Derzeit, wenn ich den Code unten ausführen, bekomme ich nur die Informationen in "OutTime". Ich weiß, warum das passiert, aber ich bin nicht sicher, wie ich es ändern kann, um die Informationen zu bekommen, die ich möchte.

Was ich möchte angezeigt werden: Alle Namen unter den "Menschen" und die "OutTime".

Beispiel:

OutPut: S7-JEHILL 20:47

XML Blatt

<Times> 
    <People> 
    <S7-JEHILL> 
     <OutTime>20:47</OutTime> 
    </S7-JEHILL> 
    </People> 
</Times> 

aktuellen 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 

Antwort

0

Verwenden Sie zuerst eine XPath-Abfrage, um alle Knoten unter dem Tag abzurufen. Dann nutzen Sie die ChildNodes Sammlungen die relevanten Informationen von a) dem Tag-Namen und b) der outtime Wert zu erhalten:

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 
0

hinzufügen System.XML auf Ihre Referenz. Dies ist nur ein weiterer Ansatz für die Manipulation von XML-Dateiknoten.

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 
Verwandte Themen