LXML + Python:如何在同一父子级别查找和使用参数

LXML + Python: How to find and work with parameters at the same parent-child level

我不确定如何解决这个问题 - 所以恐怕我还没有太多关于这个问题的代码。

我正在使用 lxml 读写 XML 文件。我有一个场景,我需要阅读的 XML 有一些组件,如下所示。我需要做的是确定 SettingProperty 是否具有特定品种的 Value_1,然后与 Value_1 一起工作。我还需要能够将 Value_1 设置为其他内容。

给出以下示例:假设我想测试设置名称 3 的值,如果 True 将其设置为 False,我该怎么做?

<?xml version="1.0" standalone="yes"?>
<ProjectDataSet>

   ... Many other bits here

  <Setting>
    <Property>Setting Name 1</Property>
    <Value_1>5</Value_1>
    <Comments>Allows values between 1 and 10, 5 is default</Comments>
  </Setting>
  <Setting>
    <Property>Setting Name 2</Property>
    <Value_1>False</Value_1>
  </Setting>
  <Setting>
    <Property>Setting Name 3</Property>
    <Value_1>True</Value_1>
    <Comments>Setting enables a True or False</Comments>
  </Setting>
  <Setting>
    <Property>Setting Name 4</Property>
    <Value_1>True</Value_1>
    <Comments>This example sets True</Comments>
  </Setting>
</ProjectDataSet>

我可以弄清楚如何只找到 Property 并根据下面的示例对其进行修改,但无法弄清楚如何识别相同 SettingValue_1 并进行更改从真到假:

import lxml

#import the xml
tree = etree.parse('C:/temp/myxml.xml')
root = tree.getroot()

#Change the current name to add "My New Property" at the end.
setNameText = root.xpath('//Setting/Property/text()')
setName = root.xpath('//Setting/Property')
     if setName:
          setName[0].text = setNameText[0] + " My New Property"

谢谢

为了“测试 Setting Name 3 的值,如果 True 将其设置为 False”,我相信您需要这样的东西:

targets = root.xpath("//Setting[./Property[.='Setting Name 3']]")
for target in targets:
    val = target.xpath('./Value_1')[0]
    if val.text=="True":
        val.text="False"
print(etree.tostring(root).decode())

根据上面的示例 xml,输出应为:

<ProjectDataSet>
  <Setting>
    <Property>Setting Name 1</Property>
    <Value_1>5</Value_1>
    <Comments>Allows values between 1 and 10, 5 is default</Comments>
  </Setting>
  <Setting>
    <Property>Setting Name 2</Property>
    <Value_1>False</Value_1>
  </Setting>
  <Setting>
    <Property>Setting Name 3</Property>
    <Value_1>False</Value_1>
    <Comments>Setting enables a True or False</Comments>
  </Setting>
  <Setting>
    <Property>Setting Name 4</Property>
    <Value_1>True</Value_1>
    <Comments>This example sets True</Comments>
  </Setting>
</ProjectDataSet>