python lxml - modify attributes

前端 未结 2 1836
别跟我提以往
别跟我提以往 2020-12-09 16:09
from lxml import objectify, etree

root = etree.fromstring(\'\'\'


    

        
相关标签:
2条回答
  • 2020-12-09 16:33
    import lxml.etree as et
    
    tree = et.fromstring('''
    ... your xml ...
    ''')
    
    for host_ip in tree.xpath("/scenario/init/send/command[@name='CER']/avp[@name='Host-IP-Address']"):
        host_ip.attrib['value'] = 'foo'
    
    print et.tostring(tree)
    
    0 讨论(0)
  • 2020-12-09 16:34

    You could try this:

    r = etree.fromstring('...')
    
    element = r.find('//avp[@name="Host-IP-Address"]')
    
    # Access value
    print 'Current value is:', element.get('value')
    
    # change value
    element.set('value', 'newvalue')
    

    Also, note that in your example you're using the text() method, but that's not what you want: the "text" of an element is what is enclosed by the element. For example, given this:

    <someelement>this is the text</someelement>
    

    The value of the text() method on the <somevalue> element is "this is the text".

    0 讨论(0)
提交回复
热议问题