當創建了這樣一個System.Xml.Linq.XDocument一個文檔類型:HTML 5的文檔類型添加到的XDocument(.NET)
doc.AddFirst(new XDocumentType("html", null, null, null));
產生的保存XML文件的開頭爲:
<!DOCTYPE html >
注意關閉角度支架前的額外空間。 如何防止出現此空間? 我想要一個乾淨的方式,如果可能的話:)
當創建了這樣一個System.Xml.Linq.XDocument一個文檔類型:HTML 5的文檔類型添加到的XDocument(.NET)
doc.AddFirst(new XDocumentType("html", null, null, null));
產生的保存XML文件的開頭爲:
<!DOCTYPE html >
注意關閉角度支架前的額外空間。 如何防止出現此空間? 我想要一個乾淨的方式,如果可能的話:)
一種方法是寫一個包裝類的的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);
}
}
不是一個特別乾淨的解決方案,但它會完成這項工作。
我可能是錯的,但我認爲這個空間是因爲在HTML之後有更多的參數。雖然HTML5允許。
嘗試指定至少第三個參數(* .dtd)。 或者做這樣的事情:
new XDocumentType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", null)
這打破了使用不太重要的HTML5文檔類型的觀點。 – hsivonen 2009-09-14 10:32:50
,如果你寫一個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,讓我通過設置。 – 2009-09-13 14:20:09
在Reflector中繞了一圈之後,似乎XmlTextWriter和XmlEncodedRawTextWriter的WriteDocType的實現略有不同。這說明了額外的空間特徵。 – 2009-09-13 14:35:36
我現在正在做類似的事情:用底層TextWriter手動編寫doctype,然後使用XmlWriter編寫XDocument。我不再添加XDocumentType對象。 – 2009-09-14 08:30:43