给XDocument(.NET)添加HTML 5 doctype

3
创建System.Xml.Linq.XDocument的doctype时,可以按照以下格式:
doc.AddFirst(new XDocumentType("html", null, null, null));

生成的保存为XML文件以以下内容开头:
<!DOCTYPE html >

注意在闭合尖括号前的额外空格。 如何避免出现这个空格? 如果可能的话,我想要一种简洁的方式 :)
3个回答

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();
}

有趣的是,但这样我就无法设置Settings属性来省略XML声明。我正在使用XmlWriter.Create,它允许我传递设置。 - Andrew Davey
1
在 Reflector 中进行了一些探索后,似乎 XmlTextWriter 和 XmlEncodedRawTextWriter 在 WriteDocType 的实现上略有不同。这就解释了额外的空格字符。 - Andrew Davey

3
一种方法是编写一个XmlWriter的包装类。因此:
XmlWriter writer = new MyXmlWriterWrapper(XmlWriter.Create(..., settings))

然后针对MyXmlWriterWrapper类,为XmlWriter类接口的每个方法定义一个方法,以直接将调用传递到包装的写入器,除了WriteDocType方法。 然后您可以将其定义为类似于以下内容:

public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
    if ((pubid == null) && (sysid == null) && (subset == null))
    {
        this.wrappedWriter.WriteRaw("<!DOCTYPE HTML>");
    }
    else
    {
        this.wrappedWriter.WriteDocType(name, pubid, sysid, subset);
    }
}

虽然不是特别干净的解决方案,但它能胜任工作。


我现在正在做类似的事情:使用底层的TextWriter手动编写doctype,然后使用XmlWriter编写XDocument。我不再添加XDocumentType对象了。 - Andrew Davey

0

我可能错了,但我认为这个空格是因为在 HTML 后面还有更多的参数。虽然 HTML5 允许这样做。

尝试至少指定第三个参数(*.dtd)。 或者像这样做:

new XDocumentType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", null)

2
这将毁掉使用较少冗余的HTML5文档类型的意义。 - hsivonen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接