我如何使用 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 标记的值,要么因为没有正确处理文本而生成各种错误。
最佳答案
你已经很接近了,你只需要正确设置你的 xpath 即可。另外为什么不打印root
?
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")
for target in targets:
target.text = str(newWeatherId)
print(etree.tostring(root))
关于python - LXML + python : How to change every instance of an element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69263181/