1

我试图仅读取此 XML 文件中的值,但我无法找出正确读取此值的代码。

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>

我试图使用的代码是:

   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

代码没有返回 Key 的内容。谁能告诉我如何获取 Key 的文本内容?

4

3 回答 3

0

这应该这样做并通过使用返回您的 xml 文件中的每个键SelectNodes(而您的代码只会返回一个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

测试输出:

tmp.png
2013.png
于 2013-07-11T13:42:08.827 回答
0

我认为因为您已经指定了节点的路径,所以您应该只需要类似的东西

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

    For Each inst As XmlNode In node.ChildNodes
        MessageBox.Show(inst.InnerText)
    Next
于 2013-07-11T13:37:21.590 回答
0

我认为您可能会浪费一些处理器周期;你应该只需要:

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

因为您已经位于正确的 XML 节点。

于 2013-07-11T13:37:27.323 回答