Updating XML elements and attribute values using Python etree

前端 未结 1 388
别那么骄傲
别那么骄傲 2020-12-30 13:28

I\'m trying to use Python 2.7\'s ElementTree library to parse an XML file, then replace specific element attributes with test data, then save this as a unique X

相关标签:
1条回答
  • 2020-12-30 13:44

    For this kind of work, I always recommend 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>
    
    0 讨论(0)
提交回复
热议问题