编程语言
首页 > 编程语言> > C#-OpenXML转义非法字符

C#-OpenXML转义非法字符

作者:互联网

我正在使用OpenXML Power Tools在Word Docx文件中进行一些字符串替换,并且按预期方式工作.但是,当替换中有无效字符(例如&符)时,事情就会中断,因此“ Harry& Sally”会中断并产生无效的文档.根据this post,非法字符需要转换为xHHHH.

我在查找帖子中提到的OOXML子句的内容时遇到了麻烦,因此无法适当地转义字符.

我希望有人对某些字符或需要转义的字符有所了解.我也希望OpenXML Power Tools能以某种方式为我做到这一点,但是我似乎也找不到任何东西.

解决方法:

该规范只是在谈论必须在XML中转义的标准字符集.链接文章中提到的XML规范是W3C的found here.

除非它们是CDATA节的一部分,否则有五个字符需要在XML数据中出现的任何位置(名称,值等)进行转义.根据第2.4节:

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 " &amp; " and " &lt; " respectively. The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility, be escaped using either " &gt; " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (‘) may be represented as " &apos; ", and the double-quote character (“) as " &quot; ".

换句话说,请转义以下字符:

' -> &apos;
" -> &quot;
> -> &gt;
< -> &lt;
& -> &amp;

通常,您不会将它们编码为xHHHH,而是使用上面列出的XML实体,但任何一个都可以.您也不需要在每种情况下都只对引号或直角括号进行编码,仅当它们会以其他方式表示XML语法时,通常这样做总是更安全.

XML规范在第2.2节中还包括可以在XML文档中出现的每个Unicode字符的列表:

Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

该列表基本上包括Basic平面中的每个Unicode字符(您可能会遇到的每个字符),但控制字符除外.仅允许使用制表符,CR和LF字符-低于ASCII 32(空格)的任何其他字符都需要转义.

列表(0xD800-0xDFF)中的最大空白是代理编码值,因为它们不是有效字符,因此它们本身也不应该出现.最后两个0xFFFE和0xFFFF也是无效字符.

标签:c,openxml-sdk
来源: https://codeday.me/bug/20191028/1953066.html