我的页面上有一个XmlDataSource和一个GridView。在Page_Load事件上,我应用了一个XPath根据用户LexiqueXmlDataSource.XPath = 'Some_XPath_here';
的输入过滤xml元素,并且工作正常。
我想要的是在应用XPath表达式后访问XmlDataSource从代码隐藏返回的元素(并因此获取它们的编号)。
我尝试了GetXmlDocument()
方法,但它返回了整个原始Xml文件,而不是使用XPath过滤的元素。
编辑:
这是一些代码和我想要的方案:
protected void Page_Load(object sender, EventArgs e)
{
string xpath = "/lexique/item[starts-with(@acronym, '" + filter + "')]";
LexiqueXmlDataSource.XPath = xpath;
// Here the XmlDataSource have filtered the xml elements to return to the GridView
//I want to know how many element passed this filter using the XmlDataSource itself
}
谢谢。
最佳答案
这是我能想到的。
对于点击数。使用GridView行计数。实际上,GetXmlDocument.ChildNodes.Count总是返回词汇项的数量,而不是应用XPath表达式时的命中数。
测试XML
<?xml version="1.0" encoding="utf-8" ?>
<lexique>
<item acronym="WPF" value="Windows Presentation Foundation"/>
<item acronym="SO" value="StackOverflow"/>
</lexique>
极简ASP.net页面
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="xmlgrid.aspx.vb" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="FilterLabel" runat="server" Text="Acronym starting with:"></asp:Label>
<asp:TextBox ID="FilterTextBox" runat="server"></asp:TextBox>
<asp:XmlDataSource ID="LexiqueXmlDataSource" runat="server" DataFile="~/lexique.xml">
</asp:XmlDataSource>
<asp:GridView ID="LexiqueGrid" runat="server" AllowSorting="true" BorderStyle="Groove">
<Columns>
<asp:TemplateField HeaderText="Acronym">
<ItemTemplate>
<%# XPath("/lexique/item/@acronym")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<%# XPath("/lexique/item/@value")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Hits" runat="server" Text="Acronyms found"></asp:Label>
<asp:Button ID="Submit" runat="server" Text="Search" />
</div>
</form>
</body>
</html>
背后的代码
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim XPath As String
If String.IsNullOrEmpty(FilterTextBox.Text) Then
XPath = "/lexique/item"
Else
XPath = "/lexique/item[starts-with(@acronym, '" + FilterTextBox.Text + "')]"
End If
LexiqueXmlDataSource.XPath = XPath
LexiqueXmlDataSource.DataBind()
LexiqueGrid.DataSource = LexiqueXmlDataSource
LexiqueGrid.DataBind()
Hits.Text = "Selected " & LexiqueGrid.Rows.Count & " out of " &
LexiqueXmlDataSource.GetXmlDocument.ChildNodes.Count & "Acronyms loaded."
End Sub
End Class
关于xpath - 在后面的代码中循环遍历XmlDataSource中的XML元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4981012/