What does <![CDATA[]]> in XML mean?

前端 未结 13 2214
独厮守ぢ
独厮守ぢ 2020-11-21 07:52

I often find this strange CDATA tag in XML files:


I have observed that this CD

13条回答
  •  面向向阳花
    2020-11-21 08:18

    A CDATA section is "a section of element content that is marked for the parser to interpret as only character data, not markup."

    Syntactically, it behaves similarly to a comment:

    
    
    
    

    ... but it is still part of the document:

    
     < " and &
        or write things like
        
        but my document is still well formed!
    ]]>
    
    

    Try saving the following as a .xhtml file (not .html) and open it using FireFox (not Internet Explorer) to see the difference between the comment and the CDATA section; the comment won't appear when you look at the document in a browser, while the CDATA section will:

    
    
    
    
    CDATA Example
    
    
    
    

    Using a Comment

    Using a CDATA Section

    & " ]]>

    Something to take note of with CDATA sections is that they have no encoding, so there's no way to include the string ]]> in them. Any character data which contains ]]> will have to - as far as I know - be a text node instead. Likewise, from a DOM manipulation perspective you can't create a CDATA section which includes ]]>:

    var myEl = xmlDoc.getElementById("cdata-wrapper");
    myEl.appendChild(xmlDoc.createCDATASection("This section cannot contain ]]>"));
    

    This DOM manipulation code will either throw an exception (in Firefox) or result in a poorly structured XML document: http://jsfiddle.net/9NNHA/

提交回复
热议问题