Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

xml - python lxml - modify attributes

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>''')

How can I modify/set both values?

  • Host-IP-Address value="0x00010a248921"

  • "Vendor-Id" value="11"

I've unsuccessfully tried accessing

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

Goal: I'd preferably like to see a lxml.objectify vs an Xpath solution but I'll accept other lxml based solutions.

The files are <100kB so speed/RAM is not much of a concern.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...