0

我试图找到一种缩进 HTML 文件的方法,我一直在使用 XMLDocument 并且只使用 XmlTextWriter。

但是我无法为 HTML 文档正确格式化它,因为它会检查 doctype 并尝试下载它。

是否存在不验证或检查文档并尽最大努力缩进的“愚蠢”缩进机制?这些文件大小为 4-10Mb,它们是自动生成的,我们必须在内部处理它 - 很好,用户可以等待,我只是想避免分叉到新进程等。

这是我的代码供参考

        using (MemoryStream ms = new MemoryStream())
        using (XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode))
        {
            XmlDocument doc = new XmlDocument();
            // LoadSettings the unformatted XML text string into an instance
            // of the XML Document Object Model (DOM)
            doc.LoadXml(content);

            // Set the formatting property of the XML Text Writer to indented
            // the text writer is where the indenting will be performed
            xtw.Formatting = Formatting.Indented;

            // write dom xml to the xmltextwriter
            doc.WriteContentTo(xtw);

            // Flush the contents of the text writer
            // to the memory stream, which is simply a memory file
            xtw.Flush();

            // set to start of the memory stream (file)
            ms.Seek(0, SeekOrigin.Begin);

            // create a reader to read the contents of
            // the memory stream (file)
            using (StreamReader sr = new StreamReader(ms))
                return sr.ReadToEnd();
        }

本质上,现在我使用 MemoryStream、XmlTextWriter 和 XmlDocument,一旦缩进,我就从 MemoryStream 中读取它并将其作为字符串返回。XHTML 文档和一些 HTML 4 文档会发生故障,因为它试图抓取 dtds。我尝试将 XmlResolver 设置为 null 但无济于事:(

4

1 回答 1

0

如果无法访问导致问题的特定 X[H]TML,很难知道这是否可行,但您是否尝试过使用它XDocument

XDocument xdoc = XDocument.Parse(xml);
string formatted = xdoc.ToString();
于 2010-04-30T01:50:43.317 回答