python - LXML + python : How to change every instance of an element

标签 python python-3.x lxml

我如何使用 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/

相关文章:

python - 检测 Python 代码

python - 在 sqlalchemy、数据库、ORM 中使用标签

python - 使用 lxml 解析 Yelp - 忽略 html 标签

python - 如何在 Python 和 LXML 中解析 XML?

Python KMeans 聚类单词

javascript - 在 JavaScript 中向用户隐藏 Solr 服务器 URL

python - 对具有多个大小值的字典进行排序

python - PyCharm 类型检查没有按预期工作

python - 无法在 OS X 10.8.5 上安装 lxml

python - 在linux和mac中从python查询窗口id