我正在使用一些包含字符串的XML:

<node>This is a string</node>

我传递给节点的一些字符串将有&,#,$等字符:

<node>This is a string & so is this</node>

由于&,这是无效的。

我不能在CDATA中包装这些字符串,因为它们需要这样。我尝试寻找一个字符列表,这些字符不能放在XML节点中,而不能放在CDATA中。

有人能给我指个方向或者给我一份非法字符的列表吗?


当前回答

ampersand (&) is escaped to &amp;

double quotes (") are escaped to &quot;

single quotes (') are escaped to &apos; 

less than (<) is escaped to &lt; 

greater than (>) is escaped to &gt;

在c#中,使用system . security . securyelement.escape或System.Net.WebUtility.HtmlEncode来转义这些非法字符。

string xml = "<node>it's my \"node\" & i like it 0x12 x09 x0A  0x09 0x0A <node>";
string encodedXml1 = System.Security.SecurityElement.Escape(xml);
string encodedXml2= System.Net.WebUtility.HtmlEncode(xml);


encodedXml1
"&lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it 0x12 x09 x0A  0x09 0x0A &lt;node&gt;"

encodedXml2
"&lt;node&gt;it&#39;s my &quot;node&quot; &amp; i like it 0x12 x09 x0A  0x09 0x0A &lt;node&gt;"

其他回答

对于Java人来说,Apache有一个实用程序类(StringEscapeUtils),它有一个帮助方法escapeXml,可以用来使用XML实体转义字符串中的字符。

有人尝试过这个system . security . securityelelement . escape (yourstring)吗? 这将用有效的等效字符替换字符串中的无效XML字符。

对于XSL(在非常懒惰的日子里),我使用:

capture="&amp;(?!amp;)" capturereplace="&amp;amp;"

翻译所有没有遵循的&符号på amp;敬合适的人。

在某些情况下,输入是CDATA,但是使用XML的系统没有考虑到它。这是一个草率的修复,小心…

除了potame的答案,如果你想转义使用CDATA块。

如果你把你的文本放在一个CDATA块,那么你不需要使用转义。 在这种情况下,您可以使用以下范围内的所有字符:

注意:除此之外,您不允许使用]]>字符序列。因为它将匹配CDATA块的末尾。

如果仍然存在无效字符(例如控制字符),那么可能最好使用某种编码(例如base64)。

预先声明的字符是:

& < > " '

有关更多信息,请参阅“XML中的特殊字符是什么?”