Reputation: 658
I am new to programming and python. I want to learn to modify a XML file through Python 3.6. I created a XML file as in https://docs.python.org/3/library/xml.etree.elementtree.html
Exemple file:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
When I test the first block:
import xml.etree.ElementTree as ET
tree = ET.parse('C:\Program Files\Python36\programele\country_data.xml')
root = tree.getroot()
print(root)
it gives me this error:
Traceback (most recent call last):
File "C:/Program Files/Python36/programele/farmi.py", line 3, in <module>
tree = ET.parse('C:\Program Files\Python36\programele\country_data.xml')
File "C:\Program Files\Python36\lib\xml\etree\ElementTree.py", line 1196, in parse
tree.parse(source, parser)
File "C:\Program Files\Python36\lib\xml\etree\ElementTree.py", line 597, in parse
self._root = parser._parse_whole(source)
File "<string>", line None
xml.etree.ElementTree.ParseError: syntax error: line 1, column 0
I even tried this ET.fromstring(open('country_data.xml').read())
and it doesn't work.
I appreciate any advice and information.
Thank you
Upvotes: 1
Views: 4702
Reputation: 31
What I found in my case was that the xml file was invalid. That is, the file did not have the xml file Structure. What I would suggest you to do is check out the content of the xml file by opening up in a text editor and the file structure could be easily viewed.
However, if you are processing a lot of xml files, and you do not know if any your xml file is invalid, you should consider adding a "try/except" block in your Python code. Like this:
try: tree = ET.parse(file) root = tree.getroot() except: pass
Upvotes: 3