我正在处理一些包含类似字符串的XML:
<node>This is a string</node>
我传递给节点的某些字符串将具有类似&
,#
,$
等的字符:
<node>This is a string & so is this</node>
由于&
,此无效。
我无法将这些字符串原样包装在CDATA中。我尝试查找无法不放在CDATA中就不能放入XML节点的字符列表。
有人可以指出我的方向或向我提供一系列非法字符吗?
[唯一的非法字符是&
,<
和>
(以及属性中的"
或'
)。
string code = Regex.Replace(item.Code, @"[\u0000-\u0008,\u000B,\u000C,\u000E-\u001F]", "");
在C#中,使用ampersand (&) is escaped to &
double quotes (") are escaped to "
single quotes (') are escaped to '
less than (<) is escaped to <
greater than (>) is escaped to >
或System.Security.SecurityElement.Escape
转义这些非法字符。
[对于Java专家来说,Apache的实用程序类(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>"
)具有帮助程序方法StringEscapeUtils
,可用于使用XML实体对字符串中的字符进行转义。
在Woodstox XML处理器中,无效字符通过以下代码分类:
escapeXml
总而言之,文本中的有效字符是:
有人尝试过此]]
吗?这会将字符串中的无效XML字符替换为有效的等效字符。
对于XSL(在非常懒惰的日子),我使用:
[好,让我们分开以下字符的问题:
有效字符列表在XML specification中:
这是C#代码,用于从字符串中删除XML无效字符并返回新的有效字符串。
预先声明的字符是:
逃避C#中潜在有害XML / XHTML字符的另一种简便方法是:
除了potame的答案,如果您确实想使用CDATA块进行转义。
删除C#中不正确的XML字符的另一种方法是使用XmlConvert.IsXmlChar
(自.NET Framework 4.0起可用)
“ \v
”为我工作
XmlWriter and lower ASCII characters