Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

html - Self-closing tags in XML files

<tag id="foo" />

I noticed that they work with PHP SimpleXML.

But all XML examples I found on the web close them the old way:

<tag id="foo"></tag>

Is there any reason why I should use the old method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See the W3C specs for XML and XHTML:

It depends on the Element Type declaration

An element with no content is said to be empty. The representation of an empty element is either a start-tag immediately followed by an end-tag, or an empty-element tag.

but also

Empty-element tags may be used for any element which has no content, whether or not it is declared using the keyword EMPTY. For interoperability, the empty-element tag SHOULD be used, and SHOULD only be used, for elements which are declared EMPTY.

This means, when your DTD contains something like

<!ELEMENT img EMPTY>

you should use

<img/>

unless you have good reason to use

<img></img>

Note that SHOULD is defined in RFC2119 as

This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.

If you are working with XML that does not have a DTD or Schema, you can also influence how the XML is serialized with a predefined libxml constant:

LIBXML_NOEMPTYTAG (integer): Expand empty tags (e.g. <br/> to <br></br>)

But note that this option is currently just available in the functions DOMDocument::save and DOMDocument::saveXML, so you cannot use it with SimpleXml.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...