从xml文件搜索数据集

时间:2010-02-24 16:45:06

标签: xml dataset filter

我需要过滤加载xml文件时获得的结果。例如,我需要在xml数据中搜索关键字“Chemistry”的项目。下面的xml示例是我的xml文件的摘要。数据加载在gridview中。你能帮忙吗?谢谢!

Xml文件(摘要):

<CONTRACTS>           <CONTRACT>           <CONTRACTID>779</CONTRACTID>           <NAME>ContractName</NAME>           <KEYWORDS>Chemistry, Engineering, Chemical</KEYWORDS>           <CONTRACTSTARTDATE>1/8/2005</CONTRACTSTARTDATE>           <CONTRACTENDDATE>31/7/2008</CONTRACTENDDATE>           <COMMODITIES><COMMODITY><COMMODITYCODE>CHEM</COMMODITYCODE>           <COMMODITYNAME>Chemicals</COMMODITYNAME></COMMODITY></COMMODITIES>           </CONTRACT></CONTRACTS>

代码背后的代码是:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim ds As DataSet = New DataSet()

    ds.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "/testxml.xml")

    Dim dtContract As DataTable = ds.Tables(0)
    Dim dtJoinCommodities As DataTable = ds.Tables(1)
    Dim dtCommodity As DataTable = ds.Tables(2)
    dtContract.Columns.Add("COMMODITYCODE")
    dtContract.Columns.Add("COMMODITYNAME")

    Dim count As Integer = 0
    Dim commodityCode As String = Nothing
    Dim commodityName As String = Nothing

    Dim dRowJoinCommodity As DataRow
    Dim trimChar As Char() = {","c, " "c}

    Dim textboxstring As String = "KEYWORDS like 'pencil'"

        For Each dRow As DataRow In dtContract.Select(textboxstring)

        commodityCode = ""
        commodityName = ""

        count = dtContract.Rows.IndexOf(dRow)
        dRowJoinCommodity = dtJoinCommodities.Rows(count)

        For Each dRowCommodities As DataRow In dtCommodity.Rows
            If dRowCommodities("COMMODITIES_Id").ToString() = dRowJoinCommodity("COMMODITIES_ID").ToString() Then

                commodityCode = commodityCode + dRowCommodities("COMMODITYCODE").ToString() + ", "

                commodityName = commodityName + dRowCommodities("COMMODITYNAME").ToString() + ", "

            End If

        Next

       commodityCode = commodityCode.TrimEnd(trimChar)
        commodityName = commodityName.TrimEnd(trimChar)
        dRow("COMMODITYCODE") = commodityCode
        dRow("COMMODITYNAME") = commodityName

    Next


    GridView1.DataSource = dtContract
    GridView1.DataBind()
End Sub

1 个答案:

答案 0 :(得分:0)

我必须建议您查看XQuery以及如何在VB中使用它,因为它专为这种情况而设计。像大多数语言一样,它有点令人生畏,但它非常强大,并且会让你做的事情变得微不足道。

XQuery是一种用于描述XML搜索的语言。 XPath是一个搜索字符串,用于描述XML中的东西的“路径”。您可以通过元素名称,元素值,属性名称/值等轻松查找内容。

不幸的是我不知道Visual Basic并且因为我大约16岁而没有使用它所以我无法帮助你,对不起。但是你永远不会后悔学习如何使用XQuery。它确实展现了XML的真正力量。

对于它的价值(在你弄清楚如何在VB中使用XQuery之前肯定不是很多),这里有一些关于配置XPath搜索的例子:

http://wxww.w3schools.com/xpath/xpath_functions.asp

再一次,不要被它吓倒,只需找到一些基本的XQuery教程,你就可以立刻搞清楚。 :)