82

I've heard that using single quotes to surround XML attribute values is a "bad style". Is this correct?

Should I always write:

<element attr="value">

Or is it acceptable to write:

<element attr='value'>

Or does it not matter which style I use?

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
  • possible duplicate of [What's the accepted way of storing quoted data in XML?](http://stackoverflow.com/questions/150423/whats-the-accepted-way-of-storing-quoted-data-in-xml) – Cody Gray - on strike Jul 23 '11 at 12:53
  • 8
    @Cody Gray - the question you link to is asking about escaping _within_ the element value, not in the element declaration (ie. around attribute values). – Oded Jul 23 '11 at 12:56

2 Answers2

105

Both are legal. Choose one and stick with it. It doesn't matter.

From the spec:

AttValue       ::=      '"' ([^<&"] | Reference)* '"'
                     |  "'" ([^<&'] | Reference)* "'"

Showing that both are valid, as is mixing the two styles within an element, per attribute (though I suggest being consistent within any single document/set of documents).

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Side note: double quotes seem to be more common, but single quotes can be embedded in JSON without escape characters (For that inevitable service-in-transition that tunnels some bit of XML in JSON :O). Handy during ad-hoc testing when you want to be able to manually extract the XML out of a JSON payload. – user2077221 Oct 01 '21 at 23:53
31

Double quotes are more usual, and it's quite acceptable for any particular community to adopt a house style for the sake of consistency, but a blanket statement that one way of doing it is better has no justification.

It's also dangerous to make such recommendations, since it encourages the "desperate perl hackers" who try to parse XML using regular expressions instead of using a real XML parser, and invariably only succeed in handling a subset of what XML legally allows.

I tend to use single quotes for convenience if I'm hand-generating XML from Java applications - though I'm increasingly inclining to the view that hand-generating XML is almost as dangerous as hand-parsing it.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164