2016-10-04 300 views
-2

在蟒蛇,只是試圖解析XML:錯誤試圖使用python解析XML:xml.etree.ElementTree.ParseError:語法錯誤:第1行,

import xml.etree.ElementTree as ET 
data = 'info.xml' 
tree = ET.fromstring(data) 

,但得到的錯誤:

Traceback (most recent call last): 
File "C:\mesh\try1.py", line 3, in <module> 
tree = ET.fromstring(data) 
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1312, in XML 
return parser.close() 
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1665, in close 
self._raiseerror(v) 
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1517, in _raiseerror 
raise err 
xml.etree.ElementTree.ParseError: syntax error: line 1, column 0 

這就是一點的XML,我有:

<?xml version="1.0" encoding="utf-16"?> 
<AnalysisData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<BlendOperations OperationNumber="1"> 
<ComponentQuality> 
    <MaterialName>Oil</MaterialName> 
    <Weight>1067.843017578125</Weight> 
    <WeightPercent>31.545017776585109</WeightPercent> 

爲什麼會發生?

+2

'fromstring()'預計該字符串包含實際的XML代碼,而不是一個_filename_。 –

回答

3

您試圖解析字符串'info.xml'而不是文件的內容。您可以撥打tree = ET.parse('info.xml')打開文件。

或者你也可以直接讀取文件:

ET.fromstring(open('info.xml').read())

+0

非常感謝!這真是一個愚蠢的錯誤。 –