【问题标题】:.NET: Possible to change XPath() expression based on URL parameters?.NET:可以根据 URL 参数更改 XPath() 表达式吗?
【发布时间】:2010-10-01 00:57:08
【问题描述】:

我正在设置一个简单的页面,它只显示 XML 文件的内容并允许用户按关键字过滤。

我是一个认真的 .NET 新手,但我已经设置了 XmlDataSource:

<asp:XmlDataSource ID="RSSFeedDataSource" runat="server"  DataFile="test.xml"
        XPath="/rss/channel/item[contains(title,"theKeyword")]"></asp:XmlDataSource>

所以我想让用户输入一个关键字并根据它更改数据源。

我想我会使用来自文本输入的关键字进行回发,获取该关键字并以某种方式插入到 XPath 表达式中...

我现在是为了简单起见,但这会是最简单的方法吗?

【问题讨论】:

    标签: .net xpath filter


    【解决方案1】:

    您可以在页面本身内执行此操作,如下所示:

    <asp:XmlDataSource ID="RSSFeedDataSource" runat="server" 
      DataFile="test.xml"
      XPath="/rss/channel/item[contains(title,"<%=Request.QueryString["filter"] %>")]"></asp:XmlDataSource>
    

    如果这不起作用,为什么不使用查询字符串或发布值在代码隐藏中设置 XPath 属性?

    【讨论】:

      【解决方案2】:

      通过后面的代码和按钮回发获取它的方法

      ASP 页面:

      <asp:TextBox id="txtKeyword" runat="server" />
      <asp:Button id="btnKeyword" OnClick="btnKeyword_Click" runat="server" />
      

      后面的代码:

      public void btnKeyword_Click(Object sender, EventArgs e)
      {
        // Assuming C#
        // Retrieve the keyword from the text box
        string keyword = txtKeyword.Text
      
        // Next step would be to modify the XPath of your XmlDataSource
        RSSFeedDataSource.XPath = "/rss/channel/item[contains(title," + keyword + ")]"
      }
      

      【讨论】:

        【解决方案3】:

        在回发上,你应该可以做到

        RSSFeedDataSource.XPath = "/rss/channel/item[contains(title,'" + txtKeyword.Text + "')]";
        

        假设关键字来自 id 为 txtKeyword 的服务器控件

        【讨论】:

          猜你喜欢
          • 2014-04-11
          • 1970-01-01
          • 2015-04-15
          • 2010-09-29
          • 2015-08-09
          • 2018-09-20
          • 1970-01-01
          • 2020-04-17
          • 1970-01-01
          相关资源
          最近更新 更多