HtmlAgilityPack解析不了Html

.Net技术 码拜 8年前 (2016-03-07) 1229次浏览
各位大牛,请帮助,
求帮助目的:通过HtmlAgilityPack动态修改Html中的值,然后将Html链接返回
问题描述:无法解析Html,总是只得到1个name为#document的node
(1)Html模板如下:

<!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>
    <meta name="viewport" content="initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no" />
    <title></title>   
</head>
<body>
     <div> <input id="catagory" name="catagory" type="text" value="1111" 
             readonly="readonly" /></div>
     <div> <input id="num" name="num" type="text" value="2222" /> </div>
     <div> <input id="counter" name="counter" type="text" value="3333" /></div>        
</body>
</html>

(2)解析代码片段如下
//sourceFileName:  “/TemplateHtml/FinancialHtmlTemplate.htm”;
//Dic:找到ID为dic.key的div,将其值改为dic.value
//
public static string BuildHtml(string sourceFileName, Dictionary<string, string> dic, ref string message)
{
HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();
//以下语句结果为E:\工程项目\二维码生成器\WSApplication\TemplateHtml\FinancialHtmlTemplate.htm
string templatepath = System.Web.HttpContext.Current.Server.MapPath(sourceFileName);
hd.LoadHtml(templatepath);
foreach (KeyValuePair<string, string> d in dic)
{
string kk = string.Format(“//body/div[@id={0}]”, d.Key);
HtmlAgilityPack.HtmlNode htmlnode = hd.DocumentNode.SelectSingleNode(kk);
if (htmlnode != null)    //总是为null
{
htmlnode.SetAttributeValue(d.Key, d.Value);
}
}
hd.Save(templatepath);
return templatepath;
}

以下语句皆为空,
HtmlNode node = hd.DocumentNode.SelectSingleNode(“/html”);
HtmlNode node = hd.DocumentNode.SelectSingleNode(“//*”);
HtmlNodeCollection htmllist = hd.DocumentNode.ChildNodes;  //0个元素
讨教应该怎么处理

解决方案

20

本人这里用你的那个html模板测试了一下,本人指定了一个id值,是可以获取到的:

			HtmlDocument htmlDoc = new HtmlDocument();
			htmlDoc.Load("test.xml");
			string value = htmlDoc.GetElementbyId("catagory").Attributes["value"].Value;
			Console.WriteLine(value);
			Console.ReadKey();

HtmlAgilityPack解析不了Html
说明极有可能是你的d.Key值不对。

80

HtmlAgilityPack最新版是1.4.9,下个最新版的引用到项目里。
另外输出htmlDoc.DocumentNode.InnerHtml看看能否有东西。
为什么本人这里能正常解析的?

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明HtmlAgilityPack解析不了Html
喜欢 (0)
[1034331897@qq.com]
分享 (0)