对于这种工作,我始终建议您这样做,
BeautifulSoup因为它具有非常容易学习的API:
from BeautifulSoup import BeautifulStoneSoup as Soupxml = """<TrdCaptRpt RptID="10000001" TransTyp="0"> <RptSide Side="1" Txt1="XXXXX"> <Pty ID="XXXXX" R="1"/> </RptSide></TrdCaptRpt>"""soup = Soup(xml)rpt_side = soup.trdcaptrpt.rptsiderpt_side['txt1'] = 'Updated'rpt_side.pty['id'] = 'Updated'print soup
<trdcaptrpt rptid="10000001" transtyp="0"><rptside side="1" txt1="Updated"><pty id="Updated" r="1"></pty></rptside></trdcaptrpt>
编辑:与
xml.etree.ElementTree您可以使用以下脚本:
from xml.etree import ElementTree as etreexml = """<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)
输出示例:
<TrdCaptRpt RptID="10000001" TransTyp="0"> <RptSide Side="1" Txt1="Updated"> <Pty ID="Updated" R="1" /> </RptSide></TrdCaptRpt>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)