Skip to main content
 首页 » 编程设计

Python ElementTree 不喜欢处理指令名称中的冒号

2024年10月17日6zfyouxi

以下代码:

import xml.etree.ElementTree as ET 
 
xml = '''\ 
<?xml version="1.0" encoding="UTF-8"?> 
<testCaseConfig> 
    <?LazyComment Blah de blah/?>    
    <testCase runLimit="420" name="d1/n1"/> 
    <testCase runLimit="420" name="d1/n2"/> 
</testCaseConfig>''' 
 
root = ET.fromstring(xml) 
 
xml2 = xml.replace('LazyComment ', 'LazyComment:') 
print(xml2) 
try: 
    root2 = ET.fromstring(xml2) 
except ET.ParseError: 
    print("\nERROR in xml2!!!\n") 
 
xml3 = xml2.replace('testCaseConfig', 'testCaseConfig xmlns:Blah="http://www.w3.org/TR/html4/"', 1) 
print(xml3) 
try: 
    root3 = ET.fromstring(xml3) 
except ET.ParseError: 
    print("\nERROR in xml3!!!\n") 
    raise 

给出这个输出:

<?xml version="1.0" encoding="UTF-8"?> 
<testCaseConfig> 
    <?LazyComment:Blah de blah/?>    
    <testCase runLimit="420" name="d1/n1"/> 
    <testCase runLimit="420" name="d1/n2"/> 
</testCaseConfig> 
 
ERROR in xml2!!! 
 
<?xml version="1.0" encoding="UTF-8"?> 
<testCaseConfig xmlns:Blah="http://www.w3.org/TR/html4/"> 
    <?LazyComment:Blah de blah/?>    
    <testCase runLimit="420" name="d1/n1"/> 
    <testCase runLimit="420" name="d1/n2"/> 
</testCaseConfig> 
 
ERROR in xml3!!! 
 
Traceback (most recent call last): 
  File "C:\Users\Paddy3118\Google Drive\Code\elementtree_error.py", line 30, in <module> 
    root3 = ET.fromstring(xml3) 
  File "C:\Anaconda3\envs\Py3.5\lib\xml\etree\ElementTree.py", line 1333, in XML 
    parser.feed(text) 
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 3, column 17 

我搜索并找到了this Q指向我阅读的其他资源。

似乎'?'使其成为标签名称可以包含冒号的处理指令。没有'?那么名称中的冒号表示 namespace ,其中一个答案表明定义 namespace 应该可以正常工作。

结合'?'和 ':' 虽然会导致 ElementTree 出现问题。

我得到了这种类型的 xml 文件,这些文件被其他工具使用,这些工​​具确实解析它并且想自己使用 Python 处理这些文件。有什么想法吗?

谢谢。

请您参考如下方法:

根据 Common Syntactic Constructs 下的 W3C 可扩展标记语言 1.0 规范:

The Namespaces in XML Recommendation [XML Names] assigns a meaning to names containing colon characters. Therefore, authors should not use the colon in XML names except for namespace purposes, but XML processors must accept the colon as a name character.

并且进一步在 W3C XPath 1.0 注释中 Processing Instruction nodes :

A processing instruction has an expanded-name: the local part is the processing instruction's target; the namespace URI is null.

总的来说,<?LazyComment:Blah de blah/?>是无效的处理指令,因为冒号用于引用 namespace URI,并且用于处理该部分为 null 或空的指令。因此,Python 的 XML 处理器会提示使用这样的指令不会呈现格式良好的 XML。

此外,重新考虑生成此类无效处理指令的工具,因为它们没有处理有效的 XML 文档。可能,此类工具将 XML 文件视为文本文档(类似于您能够替换 XML 的字符串表示但无法使用 etree 附加指令的方式)。