gpt4 book ai didi

html-agility-pack - 使用 HTMLAgilitypack 通过 xpath 选择 ASPX 节点的代码示例

转载 作者:行者123 更新时间:2023-12-04 08:58:38 26 4
gpt4 key购买 nike

我想找出为什么我的代码不起作用(或者,获取一段有效示例代码)

我想做的是通过 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>

注意事项:

  1. 我知道添加命名空间 http://www.w3.org/1999/xhtml/没有意义,请告知添加命名空间的正确方法
  2. 当输入为//tr,//td 等时有效
  3. doc.DocumentNode.Descendants("asp:Content") 有效,但我需要接受用户输入的XPath,因此不会考虑(对于 LiNQ for XML 也是如此)

最佳答案

不幸的是,我无法使 XmlNamespaceManager 正确地与 HtmlAgilityPack 一起工作。但是你可以使用 xpath name()查询 asp: 类节点的函数。见:

var contentNodes = doc.DocumentNode.SelectNodes("//*[name()='asp:content']");

这将从您的片段返回 2 个 asp:content 节点。

但是使用 LINQ to XML 对此要容易得多。

关于html-agility-pack - 使用 HTMLAgilitypack 通过 xpath 选择 ASPX 节点的代码示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13562774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com