【问题标题】:Error trying parsing xml using python : xml.etree.ElementTree.ParseError: syntax error: line 1,尝试使用 python 解析 xml 时出错:xml.etree.ElementTree.ParseError:语法错误:第 1 行,
【发布时间】:2016-10-04 21:10:55
【问题描述】:

在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>

为什么会这样?

【问题讨论】:

  • fromstring() 期望字符串包含实际的 XML 代码,而不是 文件名

标签: python xml python-2.7


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2023-03-25
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 2013-12-09
    相关资源
    最近更新 更多