2016-06-22 26 views
0

XMLから2つの値を取得しようとしています。xmlから親ノードと子ノードを読み取る

現在、以下のコードを実行すると、「OutTime」に情報が表示されます。私はなぜこれが起こっているのか知っていますが、私が望む情報を得るためにそれを変更する方法がわかりません。

「People」と「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

最初にXPathクエリを使用して、タグの下にあるすべてのノードを取得します。

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

があなたの参考にSystem.XMLを追加します。その後、A)タグ名の関連情報を取得し、b)はOUTTimeは値するChildNodesコレクションを使用します。これは、XMLファイルノード操作のためのもう1つのアプローチです。

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 
関連する問題