【发布时间】:2021-09-21 03:52:05
【问题描述】:
我将如何使用 LXML 和 Python 在下面更改 Weather_ID 的每个元素?
如您所见,我基本上是在尝试将每个 Weather_Id 设置为一个新值,在本例中该值为 5。
我的真实世界示例可能有几十到几百个 Weather_Id。
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<ProjectDataSet>
<Fx>
<Id>1</Id>
<Weather_Id>2</Weather_Id>
<Other></Other>
</Fx>
<Fx>
<Id>2</Id>
<Weather_Id>2</Weather_Id>
<Other></Other>
</Fx>
<Fx>3<Id>3</Id>
<Weather_Id>2</Weather_Id>
<Other></Other>
</Fx>
<Fx>
<Id>4</Id>
<Weather_Id>2</Weather_Id>
<Other></Other>
</Fx>
</ProjectDataSet>
到目前为止我所尝试的:
from lxml import etree
text = """\
<ProjectDataSet>
<Fx>
<Id>1</Id>
<Weather_Id>2</Weather_Id>
<Other></Other>
</Fx>
<Fx>
<Id>2</Id>
<Weather_Id>2</Weather_Id>
<Other></Other>
</Fx>
<Fx>3<Id>3</Id>
<Weather_Id>2</Weather_Id>
<Other></Other>
</Fx>
<Fx>
<Id>4</Id>
<Weather_Id>2</Weather_Id>
<Other></Other>
</Fx>
</ProjectDataSet>
"""
root= etree.fromstring(text)
newWeatherId = 5
targets = root.xpath("//Fx[./Weather_Id]")
print(targets)
for target in targets:
target.text = str(newWeatherId)
我似乎没有修改列表,没有修改 Weather_Id 标记的值,或者生成了各种错误,因为我没有正确处理文本。
【问题讨论】:
标签: python python-3.x lxml