Edit XML file text based on path

后端 未结 3 453
遇见更好的自我
遇见更好的自我 2020-12-19 01:56

I have an XML file (e.g. jerry.xml) which contains some data as given below.



    2<         


        
3条回答
  •  盖世英雄少女心
    2020-12-19 02:46

    FIrst of all, documentation of how to modify an XML. Now, here is my own example:

    import xml.etree.ElementTree as ET
    
    s = """
    
        
            child text
            more child text
        
    
    """
    
    root = ET.fromstring(s)
    
    for parent in root.getchildren():
        parent.attrib['attribute'] = 'new value'
        for child in parent.getchildren():
            child.attrib['new_attrib'] = 'new attribute for {}'.format(child.tag)
            child.text += ', appended text!'
    
    >>> ET.dump(root)
    
        
            child text, appended text!
            more child text, appended text!
        
    
    

    And you can do this with Xpath as well.

    >>> root.find('parent/child_1[@other_attr]').attrib['other_attr'] = 'found it!'
    >>> ET.dump(root)
    
        
            child text, appended text!
            more child text, appended text!
        
    
    

提交回复
热议问题