The following code:
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
Gives this output:
<?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
I searched and found this Q that pointed to other resources that I read.
It seems that the '?' makes it a processing instruction whose tag name can include colons. Without the '?' then a colon in a name indicates namespace and one of the answers stated that defining the namespace should make things work.
Combining '?' and ':' though causes issues with ElementTree.
I am given xml files of this type that are used by other tools that do parse it OK and want to process the files myself using Python. Any ideas?
Thanks.