Can an XML attribute be the empty string?

2020-08-15 11:14发布

Can an XML attribute be the empty string?

In other words, is

<element att="" />

valid XML?

标签: xml
6条回答
放荡不羁爱自由
2楼-- · 2020-08-15 11:54

You can create an empty attribute via attname=""

You can create an empty element via

<elementName></elementName>

or

<elementName/>
查看更多
老娘就宠你
3楼-- · 2020-08-15 12:02

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.

查看更多
该账号已被封号
4楼-- · 2020-08-15 12:06

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.

查看更多
ら.Afraid
5楼-- · 2020-08-15 12:07

It is worth nothing that this is an XML attribute, not an element. An empty element would be:

</>

which is not valid XML.

查看更多
beautiful°
6楼-- · 2020-08-15 12:09

this is valid xml tag:

<mytag myattrib=""/>

this is not:

<mytag myattrib/>
查看更多
仙女界的扛把子
7楼-- · 2020-08-15 12:13

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.

查看更多
登录 后发表回答