[英]Python ElementTree “no element found” exception
大家好日子。
我正在嘗試使用ElementTree讀取,解析和使用xml文件。 以下數據:
<level>
<leveldata>
<level name="hh" difficulty="Easy" lenght="3600">
<meteorite chance="4" speed="3" >
<image id="1">
<image id="2">
<image id="3">
<meteorite />
<meteorite chance="4" speed="3" >
<image id="4">
<image id="5">
<image id="6">
<meteorite />
<level />
<leveldata />
<meteorimages>
<meteor id="5" imagepath="res\meteorit_1.png">
<meteor id="5" imagepath="res\meteorit_2.png">
<meteor id="5" imagepath="res\meteorit_3.png">
<meteorimages />
<datasheet />
<level />
可悲的是,我的ElementTree給了一個例外! 使用以下代碼讀取文件:
import xml.etree.ElementTree as ET
***code***
tree = ET.parse("res\\data.xml")
root = tree.getroot()
例外:
File "E:\blabla\core.py", line 26, in load_levelproperties
*tree = ET.parse("res\\data.xml")* File "E:\Programme(x86)\Python2.7x86\lib\xml\etree\ElementTree.py", line
1182, in parse
*tree.parse(source, parser)* File "E:\Programme(x86)\Python2.7x86\lib\xml\etree\ElementTree.py", line
657, in parse
*self._root = parser.close()* File "E:\Programme(x86)\Python2.7x86\lib\xml\etree\ElementTree.py", line
1654, in close
*self._raiseerror(v)* File "E:\Programme(x86)\Python2.7x86\lib\xml\etree\ElementTree.py", line
1506, in _raiseerror
***raise err xml.etree.ElementTree.ParseError: no element found: line 16, column 9***
我無法弄清楚什么是錯的,我試圖以我能想象的每種可能的方式改變data.xml,沒有區別。 它始終是文件的最后一行! 我究竟做錯了什么? 謝謝!
您的代碼未正確關閉。 例如,要關閉“隕石”標簽,請使用</meteorite>
而不是<meteorite />
。
你的XML格式不正確, ElementTree
無法解析它 - 它看起來真的像是真實文檔的一部分。
如果你格式化,這就是你得到的:
<level>
<leveldata>
<level name="hh" difficulty="Easy" lenght="3600">
<meteorite chance="4" speed="3">
<image id="1">
<image id="2">
<image id="3">
<meteorite/>
<meteorite chance="4" speed="3">
<image id="4">
<image id="5">
<image id="6">
<meteorite/>
<level/>
<leveldata/>
<meteorimages>
<meteor id="5" imagepath="res\meteorit_1.png">
<meteor id="5" imagepath="res\meteorit_2.png">
<meteor id="5" imagepath="res\meteorit_3.png">
<meteorimages/>
<datasheet/>
<level/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.