在xml的名称值对的普通字符串内部是否可以嵌入CDATA?

huangapple go评论64阅读模式
英文:

Can we embed CDATA inside the plain string of name value pair in an xml?

问题

我有一个需求,需要从具有名称值对且包含CDATA的配置xml中读取Json。

我的xml结构如下

<cfgsection name="test" value="<![CDATA[{Json数据放在这里}]]>"/>

我想知道是否可以将CDATA放在普通字符串[""]中,因为文档表明它应该在节点/元素内部?

有人能够对此进行解释吗?

英文:

I have a requirement to read Json from config xml with name value pair which has CDATA.

My xml structure looks like below

<cfgsection name="test" value="<![CDATA[{Json data goes here}]]>"/>

I would like to know can CDATA be inside a plane string [""] since the documentation suggests that it should be inside a node/element?

Can any one shed some light on this?

答案1

得分: 1

CDATA 只能作为元素内容的一部分出现,不能作为属性值的一部分出现。(如果您学会了正确的术语,提问和理解答案会更容易...)

这意味着您可以编写:

    <prop name="test"><![CDATA[{Some Json}]]></prop>

但您不能编写:

    <prop name="test" value="<![CDATA[{Some Json}]]>"/>

当然,CDATA 只是用于转义特殊字符的一种方法,在属性中还有其他转义特殊字符的方式。实际上,如果您在属性周围使用单引号

    <prop name="test" value='{"key":value, "data":[1,2,3]}'/>

那么通常情况下您不需要进行任何转义,除非您的 JSON 数据恰好包含带有 `"'"` 或 `"<"` 的字符串--在这种情况下,可以将它们写成 XML 字符引用。
英文:

CDATA can only appear as part of element content, not as part of an attribute value. (It's easier to ask questions and understand the answers if you learn the correct terminology...)

That means you can write

<prop name="test"><![CDATA[{Some Json}]]></prop>

but you can't write

<prop name="test" value="<![CDATA[{Some Json}]]>"/>

CDATA, of course is just a device for escaping special characters, and there are other ways of escaping special characters in attributes. In fact, if you use single quotes around an attribute

<prop name="test" value='{"key":value, "data":[1,2,3]}'/>

then you usually won't need any escaping at all, unless your JSON data happens to contain strings with "'" or "<" in them -- in which case they can be written as XML character references.

huangapple
  • 本文由 发表于 2020年3月17日 01:20:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/60710425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定