避免在C#中验证名称空间的XmlDocument

时间:2010-04-29 10:51:55

标签: c# xml xmldocument memorystream

我正在尝试找一种缩进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但无效:(

1 个答案:

答案 0 :(得分:0)

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

XDocument xdoc = XDocument.Parse(xml);
string formatted = xdoc.ToString();