[英]Why can't I read a XML example file. xml.etree.ElementTree.ParseError: syntax error: line 1, column 0
I am new to programming and python.我是编程和 python 的新手。 I want to learn to modify a XML file through Python 3.6.
我想学习通过 Python 3.6 修改 XML 文件。 I created a XML file as in https://docs.python.org/3/library/xml.etree.elementtree.html
我在https://docs.python.org/3/library/xml.etree.elementtree.html 中创建了一个 XML 文件
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.我什至试过这个
ET.fromstring(open('country_data.xml').read())
但它不起作用。
I appreciate any advice and information.我感谢任何建议和信息。
Thank you谢谢
What I found in my case was that the xml file was invalid.我在我的案例中发现 xml 文件无效。 That is, the file did not have the xml file Structure.
也就是说,该文件没有 xml 文件结构。 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.
我建议您做的是通过在文本编辑器中打开来查看 xml 文件的内容,并且可以轻松查看文件结构。
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.但是,如果您正在处理大量 xml 文件,并且您不知道您的 xml 文件是否无效,您应该考虑在您的 Python 代码中添加一个“try/except”块。 Like this:
像这样:
try: tree = ET.parse(file) root = tree.getroot() except: pass尝试:tree = ET.parse(file) root = tree.getroot() 除了:pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.