Can an XML attribute be the empty string?
In other words, is "<element att="" />" valid XML?
Can an XML attribute be the empty string?
In other words, is "<element att="" />" valid XML?
Yes, this is well-formed XML.
An easy way to test this (on Windows) is to save the sample in a test.xml
file and open it with Internet Explorer. IE will display an error message if the document is not well-formed.
It is worth nothing that this is an XML attribute, not an element. An empty element would be:
</>
which is not valid XML.
It should also be noted that some XML parsers will throw an error on empty string nodes and attributes instead of returning null or an empty string. So even though it might be valid, it would be better to leave it out altogether.
You can create an empty attribute via attname=""
You can create an empty element via
<elementName></elementName>
or
<elementName/>
Yes - element content can be empty, and as you used in your question there's even the special Empty-Element tag notation:
<elementname />
Except when interop with SGML is necessary, the above is equivalent to
<elementname></elementname>
Attribute values can also be empty, but attributes must always be followed by an '=' and a quoted string, even if the string contains no characters.
The definitive place for this information is the XML spec: http://www.xml.com/axml/testaxml.htm
Here's what the Annotated XML Reference has to say about empty elements:
So, is this:
<img src='madonna.gif'></img>
really exactly the same as<img src='madonna.gif'/>
? As far as XML is concerned, they are. This decision was the occasion of much religious debate, with some feeling that there is an essential element between "point" and "container" type elements. And as the "for interoperability" note below makes clear, if you are using pre-1998 SGML software to process XML, there is a big difference.
note: the discussion on empty elements was due to the original wording of the posted question.
this is valid xml tag:
<mytag myattrib=""/>
this is not:
<mytag myattrib/>