Skip to main content
 首页 » 编程设计

c#之HtmlAgilityPack 将 (小于号)之后的所有内容都视为属性

2024年02月05日1398°冷暖

我有一些通过文本区域获得的输入,我将该输入转换为 html 文档,随后将其解析为 PDF 文档。

当我的用户输入小于号 (<) 时,我的 HtmlDocument 中的一切都停止了。 HtmlAgilityPack 突然将小于号之后的所有内容都作为属性处理。查看输出:

Within this Character Data block I can use double dashes as much as I want (along with <, &,="" ',="" and="" ')="" *and="" *="" %="" myparamentity;="" will="" be="" expanded="" to="" the="" text="" 'has="" been="" expanded'...however,="" i="" can't="" use="" the="" cend="" sequence(if="" i="" need="" to="" use="" it="" i="" must="" escape="" one="" of="" the="" brackets="" or="" the="" greater-than="" sign).="">

如果我只是添加

它会变得更好一点
htmlDocument.OptionOutputOptimizeAttributeValues = true; 

这给了我:

Within this Character Data block I can use double dashes as much as I want (along with <, &,= ',= and= ')= *and= *= %= myparamentity;= will= be= expanded= to= the= text= 'has= been= expanded'...however,= i= can't= use= the= cend= sequence(if= i= need= to= use= it= i= must= escape= one= of= the= brackets= or= the= greater-than= sign).=>

我已经尝试了 htmldocument 上的所有选项,但没有一个让我指定解析器不应该是严格的。另一方面,我可能能够忍受它去掉 <,但添加所有等号对我来说真的不起作用。

void Main() 
{ 
    var input = @"Within this Character Data block I can use double dashes as much as I want (along with <, &, ', and ') *and * % MyParamEntity; will be expanded to the text 'Has been expanded'...however, I can't use the CEND sequence(if I need to use it I must escape one of the brackets or the greater-than sign)."; 
 
    var htmlDoc = WrapContentInHtml(input); 
 
    htmlDoc.DocumentNode.OuterHtml.ToString().Dump(); 
} 
 
private HtmlDocument WrapContentInHtml(string content) 
{ 
    var htmlBuilder = new StringBuilder(); 
    htmlBuilder.AppendLine("<!DOCTYPE html>"); 
    htmlBuilder.AppendLine("<html>"); 
    htmlBuilder.AppendLine("<head>"); 
    htmlBuilder.AppendLine("<title></title>"); 
    htmlBuilder.AppendLine("</head>"); 
    htmlBuilder.AppendLine("<body><div id='sagsfremstillingContainer'>"); 
    htmlBuilder.AppendLine(content);  
    htmlBuilder.AppendLine("</div></body></html>"); 
 
    var htmlDocument = new HtmlDocument(); 
    htmlDocument.OptionOutputOptimizeAttributeValues = true; 
    var htmlDoc = htmlBuilder.ToString(); 
 
    htmlDocument.LoadHtml(htmlDoc); 
 
    return htmlDocument; 
} 

有没有人知道我该如何解决这个问题。

我能找到的最接近的问题是: Losing the 'less than' sign in HtmlAgilityPack loadhtml

他实际上提示 < 消失,这对我来说很好。当然,修复解析错误是最好的解决方案。

编辑: 我正在使用 HtmlAgilityPack 1.4.9

请您参考如下方法:

您的内容明显错误。这与“严格性”无关,它实际上是关于您假装一段文本是有效 HTML 的事实。事实上,您得到的结果正是因为解析器不严格。

当您需要将纯文本插入到 HTML 中时,您需要先对其进行编码,以便将所有各种 HTML 控制字符正确转换为 HTML - 例如,<必须改为 &lt;和 &至 &amp; .

处理此问题的一种方法是使用 DOM - 使用 InnerText在目标上 div ,而不是将字符串拼在一起并假装它们是 HTML。另一种是使用一些显式编码方法 - 例如 HttpUtility.HtmlEncode .