'How to handle illegal characters in XML attributes "NAME" value

Say I have a piece of XML that looks like the following:

<row Johnson&amp;Johnson="good" M&amp;Ms ="bad" /> --self closing tag

or

<row Johnson&amp;Johnson="good" M&amp;Ms ="bad" </row>

I have escaped the & character in the attribute name value but it seems like it is still illegal. Can you have attribute NAME values with escaped illegal characters? If so how?

xml


Solution 1:[1]

&, 0x26, isn't allowed in XML names:

Section 2.3, "Common Syntactic constructs"

[4]NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
[4a]NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]

Solution 2:[2]

No, you can't have an ampersand in a name of any kind. As a result, you don't have XML at all. You've just got some text that does not amount to well-formed XML.

Consider using something more like the following as an alternative:

<products>
    <product name="Johnson&amp;Johnson" quality="good"/>
    <product name="M&amp;Ms" quality="bad" />
</products>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anders Lindahl
Solution 2