我想找出为什么我的代码不起作用(或者得到一段有效的示例代码)
我正在尝试通过XPATH表达式使用HTMLAgilityPack查询ASPX文件
这是代码,如果输入// asp:content,则有0个节点
(为清楚起见,省略了Form1.designer.cs):
using hap = HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;
namespace hap_shell
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
lbl_ErrMsg.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
try
{
lbl_ErrMsg.Text = "";
hap.HtmlDocument doc = new hap.HtmlDocument();
hap.HtmlWeb hw = new hap.HtmlWeb();
doc.Load(txt_FilePath.Text);
var q = doc.DocumentNode.Descendants("asp:Content");
var cnt = q.Count();
var nodes = q.ToList();
var nav = doc.CreateNavigator();
System.Xml.XmlNamespaceManager mgr = new System.Xml.XmlNamespaceManager(nav.NameTable);
mgr.AddNamespace("asp", "http://www.w3.org/1999/xhtml/"); // "http://tempuri.org/foo");
var selNodes =nav.Select(txt_xpath.Text, mgr);
//var selNodes = doc.DocumentNode.SelectNodes(txt_xpath.Text);
if (selNodes == null)
{
lbl_ErrMsg.Text = "No nodes match your query.";
}
lbl_ErrMsg.Text = selNodes.Count.ToString() + " nodes selected";
}
catch (Exception ex)
{
lbl_ErrMsg.Text = (ex.Message);
}
}
}
}
这是测试aspx,请保存到文件,然后将其完整路径输入txt_FilePath:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="back_cal.aspx.cs" Inherits="EDP_SYS.back_cal" %>
<asp:content id="Content1" contentplaceholderid="HeadContent" runat="server" >
</asp:content>
<asp:content id="Content2" contentplaceholderid="MainContent" runat="server">
<table>
<tr><td>
<asp:button id="Button1" runat="server" text="Search"></asp:button></td></tr>
</table>
</asp:content>
注意:
我知道添加名称空间http://www.w3.org/1999/xhtml/没有任何意义,请告知添加名称空间的正确方法
当输入为// tr,// td等时有效
doc.DocumentNode.Descendants(“ asp:Content”)可以工作,但是我需要接受用户输入的XPath,因此不会考虑使用(与XML的LiNQ相同)
最佳答案
不幸的是,我无法使XmlNamespaceManager
与HtmlAgilityPack一起正常工作。但是您可以使用xpath name()
函数来查询类似asp:
的节点。看到:
var contentNodes = doc.DocumentNode.SelectNodes("//*[name()='asp:content']");
这将从片段中返回2个
asp:content
节点。但是为此使用LINQ to XML要容易得多。