Skip to content Skip to sidebar Skip to footer

Add Html 5 Doctype To Xdocument (.net)

When creating a doctype for an System.Xml.Linq.XDocument like this: doc.AddFirst(new XDocumentType('html', null, null, null)); The resulting saved XML file starts with:

Solution 1:

You don't get the space if you write to an XmlTextWriter:

XDocumentdoc=newXDocument();
doc.AddFirst(newXDocumentType("html", null, null, null));
doc.Add(newXElement("foo", "bar"));

using (XmlTextWriterwriter=newXmlTextWriter("c:\\temp\\no_space.xml", null)) {
    writer.Formatting = Formatting.Indented;
    doc.WriteTo(writer);
    writer.Flush();
    writer.Close();
}

Solution 2:

One approach is to write a wrapper class for the XmlWriter. So:

XmlWriterwriter=newMyXmlWriterWrapper(XmlWriter.Create(..., settings))

Then for the MyXmlWriterWrapper class define each method on the XmlWriter class interface to pass the call straight through to the wrapped writer, except for the WriteDocType method. You can then define that as something like:

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

Not an especially clean solution admittedly, but it'll do the job.

Solution 3:

I might be wrong but I think this space is because there are more parameters expected after the HTML. Although HTML5 allows it.

Try specifying at least the 3rd parameter as well (*.dtd). Or do something like this:

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

Post a Comment for "Add Html 5 Doctype To Xdocument (.net)"