Quotes in XML. Single or double?

2019-01-15 05:06发布

问题:

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?

回答1:

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).



回答2:

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.