我正在使用一些包含字符串的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中。
有人能给我指个方向或者给我一份非法字符的列表吗?
当前回答
有效字符的列表在XML规范中:
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
其他回答
ampersand (&) is escaped to &
double quotes (") are escaped to "
single quotes (') are escaped to '
less than (<) is escaped to <
greater than (>) is escaped to >
在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
"<node>it's my "node" & i like it 0x12 x09 x0A 0x09 0x0A <node>"
encodedXml2
"<node>it's my "node" & i like it 0x12 x09 x0A 0x09 0x0A <node>"
有效字符的列表在XML规范中:
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
“XmlWriter和低ASCII字符”对我很有用
string code = Regex.Replace(item.Code, @"[\u0000-\u0008,\u000B,\u000C,\u000E-\u001F]", "");
综上所述,文本中的有效字符为:
制表符,换行和换行。 除&和<外,所有非控制字符都有效。 如果使用]],则>无效。
XML规范的2.2节和2.4节详细给出了答案:
字符
合法字符包括制表符、回车符、换行符以及Unicode和ISO/IEC 10646的合法字符
字符数据
The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.
唯一的非法字符是&,<和>(以及属性中的"或',这取决于使用哪个字符来分隔属性值:attr="必须使用"这里,' is allowed '和attr='必须使用'在这里,“is allowed”)。
它们是用XML实体转义的,这里你需要&&。
实际上,您应该使用一个工具或库来为您编写XML,并为您抽象这类东西,这样您就不必担心了。