Python:xml.etree.ElementTree.ParseError:格式不正确(无效令牌)

时间:2016-01-27 09:43:41

标签: python xml

我有给定的示例代码(包含xml变量),我想读取Xml的一些属性,然后更新它们。更新后,我想使用requests.post发布它们。 我得到的错误是"没有很好的形成"令牌,我无法解析xml。 请说明代码中的错误。

# -*- coding: utf-8 -*-
from xml.etree import ElementTree as etree
dataxml = """<APIDataMessage MessageID="747950743" SensorID=extref MessageDate=messagedate State="16" SignalStrength=random.randint(40,70) Voltage="2.83" Battery=random.randint(80,90) Data=random.randint(27,40) DisplayData="67.1° F" PlotValue="67.1" MetNotificationRequirements="False" GatewayID="106558" DataValues="19.5" DataTypes="TemperatureData" PlotValues="67.1" PlotLabels="Fahrenheit" />"""
parser = etree.XMLParser(encoding="utf-8")
root = etree.fromstring(dataxml, parser=parser)
root.set('SignalStrength',100)
print etree.tostring(root)

1 个答案:

答案 0 :(得分:1)

根据我的需要在代码中做:

  1. 必须在""中提供XML属性值,例如<test id="12">。这是输入SensorID=extref MessageDate=messagedate
  2. 中的错误
  3. 首先评估随机值,然后将值添加到字符串以创建完整标记。
  4. 需要set方法中的字符串,即root.set('SignalStrength','100')
  5. <强>演示

    dataxml = """<APIDataMessage MessageID="747950743" SensorID="extref"\
     MessageDate="messagedate" State="16" SignalStrength="%s" \
    Voltage="2.83" Battery="%s" Data="%s" DisplayData="67.1° F" PlotValue="67.1" \
    MetNotificationRequirements="False" GatewayID="106558" DataValues="19.5" \
    DataTypes="TemperatureData" PlotValues="67.1" PlotLabels="Fahrenheit" />"""\
    %(random.randint(40,70), random.randint(80,90), random.randint(27,40))
    
    
    from xml.etree import ElementTree as etree
    parser = etree.XMLParser(encoding="utf-8")
    root = etree.fromstring(dataxml, parser=parser)
    root.set('SignalStrength',"100")
    print etree.tostring(root)