将 HTML 5 文档类型添加到 XDocument (.NET)

And*_*vey 3 html c# xml linq-to-xml

为 System.Xml.Linq.XDocument 创建文档类型时,如下所示:

doc.AddFirst(new XDocumentType("html", null, null, null));
Run Code Online (Sandbox Code Playgroud)

生成的保存的 XML 文件开头为:

<!DOCTYPE html >
Run Code Online (Sandbox Code Playgroud)

注意右尖括号前的额外空间。如何防止出现此空间?如果可能的话,我想要一种干净的方式:)

Luk*_*vin 5

如果写入 XmlTextWriter,则不会获得空间:

XDocument doc = new XDocument();
doc.AddFirst(new XDocumentType("html", null, null, null));
doc.Add(new XElement("foo", "bar"));

using (XmlTextWriter writer = new XmlTextWriter("c:\\temp\\no_space.xml", null)) {
    writer.Formatting = Formatting.Indented;
    doc.WriteTo(writer);
    writer.Flush();
    writer.Close();
}
Run Code Online (Sandbox Code Playgroud)