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

Python ElementTree does not like colon in name of processing instruction

以下代码:

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

我搜索并发现 指向我阅读的其他资源。

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

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

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

谢谢。

<?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 xmlns:Blah="http://www.w3.org/TR/html4/">

无效XML。结束标记中不能有属性。最后一行应该只是 </testCaseConfig>

评论也是这样写的

<!-- this is a comment -->

根据 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/?> 是一个无效的处理指令,因为冒号用于引用名称空间 URI,并且对于处理指令,该部分为 null 或空。因此,Python 的 XML 处理器抱怨使用这样的指令不会呈现格式正确的 XML.

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