XML文件中的自闭标签 [英] Self-closing tags in XML files

查看:1169
本文介绍了XML文件中的自闭标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< tag id =foo/>



我注意到它们使用PHP SimpleXML 。

但是我在网上找到的所有XML示例都以旧的方式关闭它们:

< tag id =foo>< / tag>



是否有任何理由使用旧方法?

解决方案

请参阅XML和XHTML的W3C规范:

  • http://www.w3.org/TR/xml /#sec-starttags

  • http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict



  • 它取决于元素类型声明


    没有内容的元素被认为是空的。

    一个空元素的表示形式是一个紧跟着一个结束标签的开始标签或一个空元素标签。而且还包含


    空元素标记可用于任何没有内容的元素,无论是否使用关键字EMPTY声明。对于互操作性,空元素标签应该被使用,并且只能用于被声明为EMPTY的元素。


    这意味着,当你的DTD包含像

     <!ELEMENT img EMPTY> 

    使用

     < img /> 

    除非您有充足的理由使用

     < IMG>< / IMG> 

    请注意 SHOULD在RFC2119中定义为


    这个单词或形容词推荐意味着在特定情况下可能存在
    的有效理由来忽略
    特定项目,但必须理解全部含义并在选择不同课程前仔细权衡

    如果您使用的是没有DTD或架构的XML,那么您也可以通过预定义的libxml常量


    LIBXML_NOEMPTYTAG (整数):展开空标记(例如< br /> < br> ;< / br>


    但是请注意,此选项目前仅在函数中可用 DOMDocument :: save DOMDocument :: saveXML ,所以你不能在SimpleXml中使用它。

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

    这篇关于XML文件中的自闭标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆