Updating XML Elements and Attribute values using Python etree
Question: I'm very new to Python scripting, I'm trying to use 2.7 ElementTree to parse
an XML file then update/replace specific element attributes with values
sourced from a test data file. The idea is to be able to use a base XML file
to then load and populate fields with specific test data etc. then save out as
a unique XML file

My idea for a solution was to source new data from a CSV file by reading a
file to a string then slicing the string at the delimiter marks and append to
a List (done that OK). Then use etree to somehow update or delete/replace the
attribute with a specifc value from the List.

I've looked in the Python ElementTree documentation & seen the clear() and
remove() element objectsbut I've no idea of the syntax to use them adequately

An example of the XML to modify is as below, attributes with XXXXX are to be
replaced/updated:

    
    
    <TrdCaptRpt RptID="10000001" TransTyp="0">
        <RptSide Side="1" Txt1="XXXXX">
            <Pty ID="XXXXX" R="1"/>
        </RptSide>
    </TrdCaptRpt>
    

The intended result will be for example:

    
    
    <TrdCaptRpt RptID="10000001" TransTyp="0">
        <RptSide Side="1" Txt1="12345">
            <Pty ID="ABCDE" R="1"/>
        </RptSide>
    </TrdCaptRpt>
    

How do I use the etree commands to change the base XML to update with an item
from the list[]?


Answer: For this kind of work, I always recommend
[`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/) because it
has a really easy to learn API:

    
    
    from BeautifulSoup import BeautifulStoneSoup as Soup
    
    xml = """
    <TrdCaptRpt RptID="10000001" TransTyp="0">
        <RptSide Side="1" Txt1="XXXXX">
            <Pty ID="XXXXX" R="1"/>
        </RptSide>
    </TrdCaptRpt>
    """
    
    soup = Soup(xml)
    rpt_side = soup.trdcaptrpt.rptside
    rpt_side['txt1'] = 'Updated'
    rpt_side.pty['id'] = 'Updated'
    
    print soup
    

Example output:

    
    
    <trdcaptrpt rptid="10000001" transtyp="0">
    <rptside side="1" txt1="Updated">
    <pty id="Updated" r="1">
    </pty></rptside>
    </trdcaptrpt>
    

Edit: With `xml.etree.ElementTree` you could use the following script:

    
    
    from xml.etree import ElementTree as etree
    
    xml = """
    <TrdCaptRpt RptID="10000001" TransTyp="0">
        <RptSide Side="1" Txt1="XXXXX">
            <Pty ID="XXXXX" R="1"/>
        </RptSide>
    </TrdCaptRpt>
    """
    
    root = etree.fromstring(xml)
    rpt_side = root.find('RptSide')
    rpt_side.set('Txt1', 'Updated')
    pty = rpt_side.find('Pty')
    pty.set('ID', 'Updated')
    print etree.tostring(root)
    

Example output:

    
    
    <TrdCaptRpt RptID="10000001" TransTyp="0">
        <RptSide Side="1" Txt1="Updated">
            <Pty ID="Updated" R="1" />
        </RptSide>
    </TrdCaptRpt>
    

