6

Can you have an XML comment as the first line in an SVG file? For example:

<!-- Timestamp 1434061994 -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
  <svg...

Is this against SVG spec? Or would it ever fail validation or would this cause any sort of problems I'm not seeing when implementing this in a website?

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370

1 Answers1

6

Yes, it is ok to have a comment be the first line in an SVG file, but only if there is no XML declaration (<?xml version="1.0" encoding="UTF-8"?>).

Nothing can appear before the XML declaration in an XML file. At most one XML declaration can appear in a file, and if an XML declaration is used, then it must be at the very top of the file. Anything before an XML declaration, including a comment, prevents the XML from being well-formed and should result in an error such as the following diagnostic by Xerces-J:

The processing instruction target matching "[xX][mM][lL]" is not allowed.

If a comment appears before the XML declaration, then the XML is not well-formed, and if the XML is not well-formed, the SVG is not conforming.

Final note: An XML declaration is optional. Unless you want to specify a version other than 1.0 or an encoding other than UTF-8, you don't have to have an XML declaration in an XML (or SVG) file.

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • I had a comment at the top of a couple of SVGs without the XML declaration. While these SVGs worked just fine, they didn't display properly in Bitbucket diffs until I moved the comments within the SVG tag. – whatsthatitspat Mar 18 '22 at 19:47