0

问候伙计们这是我第一次访问这里我遇到了从 xml 文件中获取一些数据的问题

VB代码是

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    If (ComboBox1.Text = "") Then

        MessageBox.Show("No file name entered")

    Else


        Dim document As XmlReader = New XmlTextReader("http://gdata.youtube.com/feeds/api/users/kavvsona")

        While (document.Read())

            Dim type = document.NodeType

            If (type = XmlNodeType.Element) Then

                If (document.Name = "yt:statistics/viewCount") Then

                    xmlMyName.Visible = True
                    xmlMyName.Text = document.ReadInnerXml.ToString()

                End If

                If (document.Name = "yt:statistics/viewCount/") Then

                    xmlMyEmail.Visible = True
                    xmlMyEmail.Text = document.ReadInnerXml.ToString()

                End If

                If (document.Name = "viewCount") Then

                    xmlMyTel.Visible = True
                    xmlMyTel.Text = document.ReadInnerXml.ToString()

                End If

                If (document.Name = "Notes") Then

                    xmlMyNotes.Visible = True
                    xmlMyNotes.Text = document.ReadInnerXml.ToString()

                End If

            End If

        End While


    End If

End Sub

And the xml file is available under this link http://gdata.youtube.com/feeds/api/users/kavvsona

I want extract following information :

<yt:statistics lastWebAccess='1970-01-01T00:00:00.000Z' subscriberCount='9574' videoWatchCount='0' viewCount='120873' totalUploadViews='2374024'/>
<media:thumbnail url='http://i1.ytimg.com/i/T1ybzRP4iTT7NU6qbhV24g/1.jpg?v=51064230'/><yt:username>kavvsona</yt:username>

I have got no idea how to get it out of the yt: thing and the attribute. Please help me

谢谢

4

2 回答 2

0

对于这种 XML 解析任务,您应该使用XPath :

Imports System.Xml.XPath
...
Dim nsManager As XmlNamespaceManager = New XmlNamespaceManager(New NameTable())
nsManager.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007")

Dim xml As XDocument = XDocument.Load("http://gdata.youtube.com/feeds/api/users/kavvsona")
Dim statsElement As XElement = DirectCast(xml.XPathEvaluate("//yt:statistics", nsManager), IEnumerable).Cast(Of XElement)().Single()
Dim usernameElement As XElement = DirectCast(xml.XPathEvaluate("//yt:username", nsManager), IEnumerable).Cast(Of XElement)().Single()

Dim viewCount As Int32 = Int32.Parse(statsElement.Attribute("viewCount").Value)
Dim username As String = usernameElement.Value

MessageBox.Show(username & ": " & viewCount)

结果:

kavvsona: 120873
于 2013-06-23T14:54:56.087 回答
0

由于您使用的是 XMLTextReader 类,请查看GetAttribute方法。

于 2013-06-23T14:48:28.517 回答