求帮助目的:通过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
HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.Load("test.xml"); string value = htmlDoc.GetElementbyId("catagory").Attributes["value"].Value; Console.WriteLine(value); Console.ReadKey();
说明极有可能是你的d.Key值不对。
80