How to encode '<' & '>' Symbols in XML

北慕城南 提交于 2019-12-10 19:11:31

问题


Since < & > as part of XML syntax. How to add these symbols as part of the data like

<Note>Have to have <> symbols</Note>

I have heard there are different types of data in which XML can be sent like CDATA etc, since character data parses each character it doesn't allow these symbols.

I do know about &lt; and &gt; but that isn't helpful.

Are there are any modes of data in which XML can be sent to avoid any tool recognizing the symbols?


回答1:


There are two ways to represent characters which have special meaning in XML (such as < and >) in an XML document.

  1. CDATA sections
  2. As entities

A CDATA section can only be used in places where you could have a text node.

<foo><![CDATA[Here is some data including < and > (and &!) ]]></foo>

The caveat is that you can't include the sequence ]]> as data in a CDATA section.

Entities can be used everywhere (except inside CDATA sections) and consist of &, then an identifier, then ;.

<foo>Here is some data including &lt; and &gt; (and &amp;!)</foo>

I do know about &lt; and &gt; but that isn't helpful.

It is how XML works. It is one of your only two options. It should not be a problem (if it is, then you need to explain why in your question).




回答2:


< is encoded as &lt;.
> is encoded as &gt;.
" is encoded as &quot;.
& is encoded as &amp;.

Alternatively, you can pack the whole data in a CDATA section if it doesn't contain a CDATA section itself. If you're generating programatically, encoding each character is the better solution though.

Note that there is a plethora of XML libraries available for almost every language. Unless you want to learn about XML, I strongly recommend using an XML library instead of writing your own.




回答3:


You can encode as &amp; entity



来源:https://stackoverflow.com/questions/7818928/how-to-encode-symbols-in-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!