Do I need to declare XML on a page using the XHTML

2019-03-16 09:06发布

I've been seeing some conflicting information that an XHTML document must also declare itself as XML.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

However, in other places I'm seeing (including w3.org) that the DOCTYPE must be the first tag declaration.

Since W3 says it, it must be true. However, I probably have some pages/apps lying about that are following the first method. What are my risks?

Edit: I just ran a page through the W3 Validator with and without the XML declaration and it passed both ways. At this point, then, I'm guessing it's just a "style" thing.

4条回答
Emotional °昔
2楼-- · 2019-03-16 09:59
<?xml version="1.0" encoding="utf-8"?>

...is the default version and encoding for XML, so you don't need it at all. If you are serving XHTML as text/html, it probably shouldn't be there at all.

However, in other places I'm seeing (including w3.org) that the DOCTYPE must be the first tag.

Sounds like some confusion... DOCTYPE isn't a tag and neither is <?xml?> (which is called the XML declaration, and looks like a Processing Instruction, but it isn't one of those, either).

If you are including both, the XML declaration must come first. The trick is that IE6's DOCTYPE sniffer only detects Standards Mode DOCTYPEs if they're the first thing on the page, which means you can't use an XML declaration and you must stick with XML 1.0 and UTF-8 encoding (which is no great loss).

查看更多
Rolldiameter
3楼-- · 2019-03-16 10:02

I've never included it (always gone with just the doctype), and w3c says my XHTML 1.0 Strict projects are "valid."

查看更多
狗以群分
4楼-- · 2019-03-16 10:07

From the XHTML 1.1 specification:

An XML declaration like the one above is not required in all XML documents. XHTML document authors SHOULD use XML declarations in all their documents. XHTML document authors MUST use an XML declaration when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding is specified by a higher-level protocol.

http://www.w3.org/TR/xhtml11/conformance.html

查看更多
Juvenile、少年°
5楼-- · 2019-03-16 10:10

http://validator.w3.org/ only accepts the <?xml> stuff before <!DOCTYPE>. The other way around (doctype before ?xml) won't get validated.

查看更多
登录 后发表回答