我有给定的示例代码(包含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)
答案 0 :(得分:1)
根据我的需要在代码中做:
""
中提供XML属性值,例如<test id="12">
。这是输入SensorID=extref MessageDate=messagedate
set
方法中的字符串,即root.set('SignalStrength','100')
<强>演示强>:
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)