Python 需要通过在XML中查找父节点来更改子节点属性值

Python 需要通过在XML中查找父节点来更改子节点属性值,python,xml,python-3.x,elementtree,Python,Xml,Python 3.x,Elementtree,我有一个XML文件,我需要通过属性值找到特定的父节点,并相应地更改子节点值 我使用了下面的代码来做这件事。但它正在更改父节点属性值。我知道发生的原因和原因,但我无法找到解决办法 import xml.etree.ElementTree as ET tree=ET.parse("EditedPT.xml") root = tree.getroot() for child in root: if child.attrib["name"] == "JobStrings": ch

我有一个XML文件,我需要通过属性值找到特定的父节点,并相应地更改子节点值

我使用了下面的代码来做这件事。但它正在更改父节点属性值。我知道发生的原因和原因,但我无法找到解决办法

import xml.etree.ElementTree as ET
tree=ET.parse("EditedPT.xml")
root = tree.getroot()
for child in root:
    if child.attrib["name"] == "JobStrings":
        child.set("name","Test")
tree.write(open("EditedPT1.xml", 'w'), encoding='unicode')
XML[虚拟XML文件]

<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="1">
    <Feature name="Job">
        <Option name="Use"/>
    <Feature>
    <Feature name="Job1">
        <Option name="Use"/>
    <Feature>
</Test>

现在,我需要找到属性为
name
as
Job
的节点,并将下面的子节点
Option name=“Use”
更改为
Option name=“working”

import xml.etree.ElementTree as ET

xmlstring = '''<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="1">
    <Feature name="Job">
        <Option name="Use"/>
    </Feature>
    <Feature name="Job1">
        <Option name="Use"/>
    </Feature>
</Test>'''


root = ET.fromstring(xmlstring)
features = root.findall('.//Feature/[@name="Job"]')
for feature in features:
    feature.find('.//Option').attrib['name'] = 'working'

tree_as_str = ET.tostring(root, encoding='utf8', method='xml')
print(tree_as_str)
将xml.etree.ElementTree作为ET导入
xmlstring=''
'''
root=ET.fromstring(xmlstring)
features=root.findall('.//Feature/[@name=“Job”]'))
对于要素中的要素:
feature.find('.//Option').attrib['name']='working'
tree\u as\u str=ET.tostring(根,编码='utf8',方法='xml')
打印(树形结构)
输出

b'<?xml version=\'1.0\' encoding=\'utf8\'?>\n<Test version="1">\n    <Feature name="Job">\n        <Option name="working" />\n    </Feature>\n    <Feature name="Job1">\n        <Option name="Use" />\n    </Feature>\n</Test>'
b'\n\n\n\n\n\n\n\n\n'