Skip to main content
 首页 » 编程设计

python之xml 属性/标记中的无效 unicode 字符

2024年10月01日7bjzhanghao

xml 属性(标签)中的无效 unicode 字符列表是什么?

如下 python3 代码所示:

import xml.etree.ElementTree as ET 
from io import StringIO as sio 
 
xml_dec = '<?xml version="1.1" encoding="UTF-8"?>' 
unicode_text = '<root>textº</root>' 
valid_unicode = '<标签 属性="值">文字</标签>' 
invalid_unicode_attribute = '<tag attributeº="value">text</tag>' 
invalid_unicode_tag = '<tagº>text</tagº>' 
 
ET.parse(sio(xml_dec + unicode_text)) 
# works 
 
ET.parse(sio(xml_dec + valid_unicode)) 
# works 
 
ET.parse(sio(xml_dec + invalid_unicode_attribute)) 
# ParseError 
 
ET.parse(sio(xml_dec + invalid_unicode_tag)) 
# ParseError 

unicode字符º ,即 U+00BA , 如果它在元素文本中,则可以解析,但不能在元素属性或标记中解析。另一方面,可以在元素属性和标签中解析其他unicode字符,例如汉字。

我检查了 xml <?xml version="1.1" encoding="UTF-8"?><tagº>text</tagº>在 https://validator.w3.org/check ,它给出了错误:

Line 1, Column 43: character "º" not allowed in attribute specification list

然而,在XML Recommendation 1.1, §2.2 Characters ,它说这是允许的:

Char ::= [#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */

我的问题是,我在哪里可以找到 XML 属性/标签中的无效 unicode 字符列表?

请您参考如下方法:

对于标记和属性名称中允许的字符,W3C recommendation (你自己链接到的——但你正在查看文本节点中可以使用的内容的定义)声明如下:

Almost all characters are permitted in names, except those which either are or reasonably could be used as delimiters.

和

Document authors are encouraged to use names which are meaningful words or combinations of words in natural languages, and to avoid symbolic or white space characters in names. Note that COLON, HYPHEN-MINUS, FULL STOP (period), LOW LINE (underscore), and MIDDLE DOT are explicitly permitted.

The ASCII symbols and punctuation marks, along with a fairly large group of Unicode symbol characters, are excluded from names because they are more useful as delimiters in contexts where XML names are used outside XML documents; providing this group gives those contexts hard guarantees about what cannot be part of an XML name.

后面跟着一个 formal definition其中列出了很多 Unicode 范围:

NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | 
                  [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | 
                  [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | 
                  [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | 
                  [#x10000-#xEFFFF] 
NameChar      ::= NameStartChar | "-" | "." | [0-9] | #xB7 | 
                  [#x0300-#x036F] | [#x203F-#x2040] 
Name          ::= NameStartChar (NameChar)* 

男性序数指示符 º (#xBA) 不在其中,无论出于何种原因(至少,某些语言在常用词的缩写,所以在我看来它不像是“分隔符”)。

有趣的是,您可以在标签名称中使用数字、连字符和句点,但不能作为第一个字符。