Skip to main content
 首页 » 编程设计

python之尝试使用 python : xml. etree.ElementTree.ParseError : syntax error: line 1, 解析 xml 时出错

2025年05月04日10cyq1162

在 python 中,简单地尝试解析 XML:

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> 

为什么会这样?

请您参考如下方法:

您正在尝试解析字符串 'info.xml' 而不是文件的内容。

您可以调用 tree = ET.parse('info.xml') 来打开文件。

或者你可以直接读取文件:

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