Search code examples
.netxmlvb.netloopsxmldocument

Issue reading <key> from XML file in vb.net


I am trying to read only the value from this XML file, and I cannot figure out the code to properly read only this value.

The XML file looks like this:

<ListBucketResult>
<Name>Files</Name>
<Prefix/>
<Marker/>
<MaxKeys>1000</MaxKeys>
<IsTruncated>false</IsTruncated>
<Contents>
<Key>tmp.png</Key>
<LastModified>2013-04-30T09:25:54.000Z</LastModified>
<ETag>"49e6d7e2967d1a471341335c49f46c6c"</ETag>
<Size>561</Size>
<StorageClass>STANDARD</StorageClass>
</Contents>
<Contents>
<Key>2013.png</Key>
<LastModified>2013-05-21T12:26:15.000Z</LastModified>
<ETag>"1eea6fda0ca03698efba7b045b5375f9"</ETag>
<Size>3665</Size>
<StorageClass>STANDARD</StorageClass></Contents>
</ListBucketResult>

The code im trying to use is:

   Dim XMLFile As String = tmpdir & "tmp.xml"
    Dim xmlDoc As New XmlDocument

    xmlDoc.Load(XMLFile) 'opens XML file

    Dim node As XmlNode = xmlDoc.SelectSingleNode("/ListBucketResult/Contents/Key") 

    For Each inst As XmlNode In node.ChildNodes

        For Each sProperty As XmlNode In inst.ChildNodes



            If sProperty.Name = "key" Then

                MessageBox.Show(sProperty.Value)
            End If

        Next
    Next

The code is not returning the content of Key. Can anybody tell me how to get the text contents of Key?


Solution

  • I think you may be wasting a few processor cycles; you should only need:

    Dim nodeList As XmlNodeList = xmlDoc.SelectNodes("//Contents/Key") 
    For Each inst As XmlNode In nodeList
        MessageBox.Show(inst.InnerText)
    Next
    

    as you're already at the correct XML node.