简体   繁体   English

问题阅读 <key> 从vb.net中的XML文件

[英]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. 我正在尝试仅读取此XML文件中的值,并且我无法找出正确读取此值的代码。

The XML file looks like this: XML文件如下所示:

<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. 该代码未返回Key的内容。 Can anybody tell me how to get the text contents of Key? 有人可以告诉我如何获取Key的文本内容吗?

I think because you've specified the path to the node you should only need something like 我认为,因为您已经指定了节点的路径,所以只需要类似

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

    For Each inst As XmlNode In node.ChildNodes
        MessageBox.Show(inst.InnerText)
    Next

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. 因为您已经在正确的XML节点上。

This should do it and return every key in your xml file by using SelectNodes (whereas your code only would return one SelectSingleNode ) 这应该做到这一点,并通过使用SelectNodes返回xml文件中的每个键(而您的代码只会返回一个SelectSingleNode

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

    xmlDoc.Load(XMLFile) 'opens XML file

    Dim keyNodes = xmlDoc.SelectNodes("/ListBucketResult/Contents/Key")
    For Each singleKeyNode As XmlNode In keyNodes
        Debug.WriteLine(singleKeyNode.InnerText)
    Next

Tested Output: 测试的输出:

tmp.png
2013.png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM