循环遍历xml并添加到gridview

时间:2012-01-16 09:55:44

标签: xml vb.net gridview

我正在尝试遍历xml并将节点放入gridview中。

这是我正在使用的代码:

Dim iCustomer As XPathNodeIterator = nav.Select(nav.Compile("//Content"))
While iCustomer.MoveNext() ' Loop through all customer nodes
    ' NOW you can get those child nodes
    Dim Title As XPathNodeIterator = iCustomer.Current.SelectChildren("Title", "")
    Dim iName As XPathNodeIterator = iCustomer.Current.SelectChildren("QuickLink", "")
    Dim iContact As XPathNodeIterator = iCustomer.Current.SelectChildren("Teaser", "")

    If Title.Count <> 0 Then ' If a node is found....
        ' You *might* have to call iListID.MoveNext() here
        Title.MoveNext()
        NewRow("Content_Title") = Title.Current.Value
        ' ListID = iListID.Current.Value ' ... set the value to the string
    End If
    ' Do the above for each other value
End While

我只添加了最后一个节点,如何输出所有匹配的节点。

2 个答案:

答案 0 :(得分:0)

最简单的方法之一是使用您想要的行从xml数据填充内存中的表,然后将其绑定到gridview。我做了很多次 - 非常快。

答案 1 :(得分:0)

试试这段代码:

Dim dt As New DataTable
Dim dr As DataRow
Dim iCustomer As XPathNodeIterator = nav.Select(nav.Compile("//Content"))
While iCustomer.MoveNext() ' Loop through all customer nodes
' NOW you can get those child nodes

Dim Title As XPathNodeIterator = iCustomer.Current.SelectChildren("Title", "")
Dim iName As XPathNodeIterator = iCustomer.Current.SelectChildren("QuickLink", "")
Dim iContact As XPathNodeIterator = iCustomer.Current.SelectChildren("Teaser", "")

If Title.Count <> 0 Then ' If a node is found....
    ' You *might* have to call iListID.MoveNext() here
    Title.MoveNext()
    dr = dt.NewRow() 
    dr("Content_Title") = Title.Current.Value 
    ' ListID = iListID.Current.Value ' ... set the value to the string
    dt.Rows.Add(dr)
End If
' Do the above for each other value
End While

DataGrid.DataSource = dt