While I was learning about how to write an XHTML document with XML writer in C#, one response in my thread said I need to use XHTML namespace:
const string XHTMLNS = "http://www.w3.org/1999/xhtml";
writer.WriteStartElement("html", XHTMLNS);
writer.WriteStartElement("head", XHTMLNS);
I am not using it (I have just "html") and it works well. I am using this doctype:
writer.WriteDocType(开发者_如何学C"html","-//W3C//DTD XHTML 1.0 Transitional//EN","http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd",null);
So, I do not understand why not to use just WriteStartElement("html"), it works. Also what is benefit of using WriteStartElement("html", XHTMLNS)? Thanks!
Without using the namespaced versions you are creating an XML stream that's not valid XHTML.
This becomes a problem if and only if that output is sent to a consumer of that stream that expects to receive valid XHTML. That could be a browser or other user agent, that is told to expect XHTML by means of a content-type of "application/xhtml+xml" or it could be to a different type of consumer. For example, if you and I agree to share some data, and we decide that you will send it to me as XHTML, then my reasonable expectation would be that you would send fully valid XHTML, and if you didn't use the namespaced form then you would be failing to meet the agreement.
It's becomes more important when you consider that elements from different namespaces can all be mixed together in the same XML stream. So maybe the XHTML only makes up one or more sections of a larger XML document, with lots of elements from other namespaces as well. Then, to be able to process the document properly, the consumer needs to be able to recognise correctly the XHTML sections, and using the namespace is the way to do that.
As is frequently noted in XHTML answers on SO, by default, your generated XHTML will be sent to a browser with an "text/html" content type, so the browser is not expecting valid XHTML, or even well formed XML, but HTML instead. HTML doesn't use XML namespaces, so if that is the only consumer for your generated output, then there is no value in using the namespaced versions of the "Write" methods.
精彩评论