我正在尝试使用 HtmlAgilityPack 从头开始创建 XHTMl 文件。遵循 Add a doctype to HTML via HTML Agility pack 中提出的建议,我尝试向其中添加文档类型:
private static HtmlDocument createEmptyDoc()
{
HtmlDocument titlePage = new HtmlDocument();
titlePage.OptionOutputAsXml = true;
titlePage.OptionCheckSyntax = true;
titlePage.AddDoctype();
var html = titlePage.CreateElement("html");
titlePage.DocumentNode.AppendChild(html);
return titlePage;
}
public static class HtmlDocumentExtensions
{
public static void AddDoctype(this HtmlDocument doc)
{
var doctype = doc.DocumentNode.PrependChild(doc.CreateComment("<!doctype html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">"));
}
}
但是,当我将这个文档写入文件时,它看起来像这样:
<?xml version="1.0" encoding="iso-8859-1"?>
<!--type html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.d-->
<html />
doctype 确实被视为注释,一些字符被破折号代替。我该如何解决这个问题并将文档类型按原样写入文件?
编辑:向 HtmlDocument 添加自定义扩展
最佳答案
static void Main(string[] args)
{
string html = @"
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<table>
<tr>
<td>A!!</td>
<td>te2</td>
<td>2!!</td>
<td>te43</td>
<td></td>
<td> !!</td>
<td>.!!</td>
<td>te53</td>
<td>te2</td>
<td>texx</td>
</tr>
</table>
<h4 class=""nikstyle_title""><a rel=""nofollow"" target=""_blank"" href=""http://www.niksalehi.com/ccount/click.php?ref=ZDNkM0xuQmxjbk5wWVc1MkxtTnZiUT09&id=117""><span class=""text-matn-title-bold-black"">my text</span></a></h4>
</body>
</html>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
var doctype = doc.DocumentNode.SelectSingleNode("/comment()[starts-with(.,'<!DOCTYPE')]");
if (doctype == null)
doctype = doc.DocumentNode.PrependChild(doc.CreateComment());
doctype.InnerHtml = "<!DOCTYPE html>";
string html2 = doc.DocumentNode.InnerHtml;
}
其他问题中的代码为您提供了执行此操作的方法。这是完整的示例。
关于c# - 使用 HtmlAgilityPack 的 doctype 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27674694/