LXML + python:如何更改元素的每个实例

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

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

这就是最终采用的方法。效率低下,但实用。

curWxID = 5

fxNumber = root.xpath('//Fx/Weather_Id')
            if fxNumber:
                length = len(fxNumber)
                for i in range(length):
                    fxNumber[i].text = str(curWxID)