python lxml - 修改属性

Joa*_*edo 22 python xml lxml

from lxml import objectify, etree

root = etree.fromstring('''<?xml version="1.0" encoding="ISO-8859-1" ?>
<scenario>
<init>
    <send channel="channel-Gy">
        <command name="CER">
            <avp name="Origin-Host" value="router1dev"></avp>
            <avp name="Origin-Realm" value="realm.dev"></avp>
            <avp name="Host-IP-Address" value="0x00010a248921"></avp>
            <avp name="Vendor-Id" value="11"></avp>
            <avp name="Product-Name" value="HP Ro Interface"></avp>
            <avp name="Origin-State-Id" value="1094807040"></avp>
            <avp name="Supported-Vendor-Id" value="10415"></avp>
            <avp name="Auth-Application-Id" value="4"></avp>
            <avp name="Acct-Application-Id" value="0"></avp>
            <avp name="Vendor-Specific-Application-Id">
                <avp name="Vendor-Id" value="11"></avp>
                <avp name="Auth-Application-Id" value="4"></avp>
                <avp name="Acct-Application-Id" value="0"></avp>
            </avp>
            <avp name="Firmware-Revision" value="1"> </avp>
        </command>
    </send>
</init>

<traffic>
    <send channel="channel-Gy" >
        <action>
            <inc-counter name="HbH-counter"></inc-counter>
            ....
        </action>
    </send>
</traffic>
</scenario>''')
Run Code Online (Sandbox Code Playgroud)

如何修改/设置这两个值?

  • 主机IP地址值="0x00010a248921"

  • "Vendor-Id" 值="11"

我试图访问失败了

root.xpath("//scenario/init/send_channel/command[@name='CER']/avp[@name='Host-IP-Address']/value/text()")
Run Code Online (Sandbox Code Playgroud)

目标:我最好希望看到lxml.objectify与Xpath解决方案,但我会接受其他基于lxml的解决方案.

这些文件<100kB,因此速度/ RAM并不是很重要.

Aco*_*orn 27

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)
Run Code Online (Sandbox Code Playgroud)


lar*_*sks 8

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')
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

  • 事实证明,etree.fromstring() 实际上返回了 etree.parse() 以外的东西,这是出乎意料的。您可以使用`.//avp[@name="Host-IP-Address"]` 将路径转换为相对路径,这样就可以正常工作。“。” 代表“当前节点”。 (2认同)