Często znajduję ten dziwny znacznik CDATA
w plikach XML
:
<![CDATA[some stuff]]>
Zaobserwowałem, że ten znacznik CDATA
zawsze pojawia się na początku, a następnie po nim następują jakieś rzeczy.
Ale czasami jest on używany, czasami nie. Zakładam, że ma to na celu zaznaczenie, że jakieś rzeczy
są "danymi", które zostaną wstawione po tym. Ale jakiego rodzaju danymi są jakieś rzeczy
? Czy wszystko, co piszę w znacznikach XML nie jest jakimś rodzajem danych?
CDATA to skrót od Character Data i oznacza, że dane pomiędzy tymi ciągami zawierają dane, które mogłyby być interpretowane jako znacznik XML, ale nie powinny.
Kluczowe różnice pomiędzy CDATA a komentarzami są następujące:
]]>
(CDEnd
), podczas gdy w komentarzu --
jest nieważne.Oznacza to, że biorąc pod uwagę te trzy fragmenty XML z jednego dobrze sformowanego dokumentu:
<!ENTITY MyParamEntity "Has been expanded">
<!--
Within this comment I can use ]]>
and other reserved characters like <
&, ', and ", but %MyParamEntity; will not be expanded
(if I retrieve the text of this node it will contain
%MyParamEntity; and not "Has been expanded")
and I can't place two dashes next to each other.
-->
<![CDATA[
Within this Character Data block I can
use double dashes as much as I want (along with <, &, ', and ")
*and* %MyParamEntity; will be expanded to the text
"Has been expanded" ... however, I can't use
the CEND sequence. If I need to use CEND I must escape one of the
brackets or the greater-than sign using concatenated CDATA sections.
]]>
<description>An example of escaped CENDs</description>
<!-- This text contains a CEND ]]> -->
<!-- In this first case we put the ]] at the end of the first CDATA block
and the > in the second CDATA block -->
<data><![CDATA[This text contains a CEND ]]]]><![CDATA[>]]></data>
<!-- In this second case we put a ] at the end of the first CDATA block
and the ]> in the second CDATA block -->
<alternative><![CDATA[This text contains a CEND ]]]><![CDATA[]>]]></alternative>
Jest używany do przechowywania danych, które w przeciwnym razie mogłyby być postrzegane jako xml, ponieważ zawierają pewne znaki.
W ten sposób dane wewnątrz będą wyświetlane, ale nie będą interpretowane.