【问题标题】:Need to change the child node attribute value by finding the parent node in XML需要通过在XML中查找父节点来改变子节点属性值
【发布时间】:2019-12-18 01:20:06
【问题描述】:

我有一个 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 为Job 的节点,并将子节点Option name="Use" 更改为Option name=" working"

【问题讨论】:

    标签: python xml python-3.x elementtree


    【解决方案1】:

    下面

    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)
    

    输出

    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>'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多