c# - 使用 HtmlAgilityPack 的 doctype 问题

标签 c# html xhtml html-agility-pack

我正在尝试使用 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/

相关文章:

c# - 自动重构代码以避免无参数构造函数

c# - 从给定值的 ConcurrentDictionary 中删除键/值对

C# While 在工作线程中循环监听命令和响应

css - Mac 上的 Chrome 和 Windows 上的 Chrome 有什么区别?

javascript - 如何强制浏览器停止解析动态插入的代码到 HTML 4?

html - dropbox.com 的多文件上传功能如何运作?

html - 多个表头

c# - Silverlight Bing 通过 SSL 映射

css - 在右边界画三 Angular 形

html - 无法删除 html 中特定表格的 css 定义的表格样式