我正在使用一些包含字符串的XML:
<node>This is a string</node>
我传递给节点的一些字符串将有&,#,$等字符:
<node>This is a string & so is this</node>
由于&,这是无效的。
我不能在CDATA中包装这些字符串,因为它们需要这样。我尝试寻找一个字符列表,这些字符不能放在XML节点中,而不能放在CDATA中。
有人能给我指个方向或者给我一份非法字符的列表吗?
我正在使用一些包含字符串的XML:
<node>This is a string</node>
我传递给节点的一些字符串将有&,#,$等字符:
<node>This is a string & so is this</node>
由于&,这是无效的。
我不能在CDATA中包装这些字符串,因为它们需要这样。我尝试寻找一个字符列表,这些字符不能放在XML节点中,而不能放在CDATA中。
有人能给我指个方向或者给我一份非法字符的列表吗?
当前回答
在Woodstox XML处理器中,无效字符由以下代码分类:
if (c == 0) {
throw new IOException("Invalid null character in text to output");
}
if (c < ' ' || (c >= 0x7F && c <= 0x9F)) {
String msg = "Invalid white space character (0x" + Integer.toHexString(c) + ") in text to output";
if (mXml11) {
msg += " (can only be output using character entity)";
}
throw new IOException(msg);
}
if (c > 0x10FFFF) {
throw new IOException("Illegal unicode character point (0x" + Integer.toHexString(c) + ") to output; max is 0x10FFFF as per RFC");
}
/*
* Surrogate pair in non-quotable (not text or attribute value) content, and non-unicode encoding (ISO-8859-x,
* Ascii)?
*/
if (c >= SURR1_FIRST && c <= SURR2_LAST) {
throw new IOException("Illegal surrogate pair -- can only be output via character entities, which are not allowed in this content");
}
throw new IOException("Invalid XML character (0x"+Integer.toHexString(c)+") in text to output");
来自这里
其他回答
在Woodstox XML处理器中,无效字符由以下代码分类:
if (c == 0) {
throw new IOException("Invalid null character in text to output");
}
if (c < ' ' || (c >= 0x7F && c <= 0x9F)) {
String msg = "Invalid white space character (0x" + Integer.toHexString(c) + ") in text to output";
if (mXml11) {
msg += " (can only be output using character entity)";
}
throw new IOException(msg);
}
if (c > 0x10FFFF) {
throw new IOException("Illegal unicode character point (0x" + Integer.toHexString(c) + ") to output; max is 0x10FFFF as per RFC");
}
/*
* Surrogate pair in non-quotable (not text or attribute value) content, and non-unicode encoding (ISO-8859-x,
* Ascii)?
*/
if (c >= SURR1_FIRST && c <= SURR2_LAST) {
throw new IOException("Illegal surrogate pair -- can only be output via character entities, which are not allowed in this content");
}
throw new IOException("Invalid XML character (0x"+Integer.toHexString(c)+") in text to output");
来自这里
唯一的非法字符是&,<和>(以及属性中的"或',这取决于使用哪个字符来分隔属性值:attr="必须使用"这里,' is allowed '和attr='必须使用'在这里,“is allowed”)。
它们是用XML实体转义的,这里你需要&&。
实际上,您应该使用一个工具或库来为您编写XML,并为您抽象这类东西,这样您就不必担心了。
除了potame的答案,如果你想转义使用CDATA块。
如果你把你的文本放在一个CDATA块,那么你不需要使用转义。 在这种情况下,您可以使用以下范围内的所有字符:
注意:除此之外,您不允许使用]]>字符序列。因为它将匹配CDATA块的末尾。
如果仍然存在无效字符(例如控制字符),那么可能最好使用某种编码(例如base64)。
预先声明的字符是:
& < > " '
有关更多信息,请参阅“XML中的特殊字符是什么?”
对于XSL(在非常懒惰的日子里),我使用:
capture="&(?!amp;)" capturereplace="&amp;"
翻译所有没有遵循的&符号på amp;敬合适的人。
在某些情况下,输入是CDATA,但是使用XML的系统没有考虑到它。这是一个草率的修复,小心…