【问题标题】:LXML + python: How to change every instance of an elementLXML + python:如何更改元素的每个实例
【发布时间】: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


    【解决方案1】:

    你已经接近了,你只需要设置你的 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))
    

    【讨论】:

    • 非常感谢。我也尝试过这些方法,但由于某种原因无法正常工作。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 2012-01-12
      • 2017-01-05
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多