我正在尝试只读取此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的文本内容?
答案 0 :(得分:0)
我认为因为你已经指定了节点的路径,你应该只需要像
这样的东西 Dim node As XmlNode = xmlDoc.SelectSingleNode("/ListBucketResult/Contents/Key")
For Each inst As XmlNode In node.ChildNodes
MessageBox.Show(inst.InnerText)
Next
答案 1 :(得分:0)
我认为你可能会浪费几个处理器周期;你应该只需要:
Dim nodeList As XmlNodeList = xmlDoc.SelectNodes("//Contents/Key")
For Each inst As XmlNode In nodeList
MessageBox.Show(inst.InnerText)
Next
因为您已经在正确的XML节点上。
答案 2 :(得分:0)
这应该这样做并使用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
测试输出:
tmp.png
2013.png