python lxml add element

This is the place for queries that don't fit in any of the other categories.

python lxml add element

Postby mah454 » Mon Jun 17, 2013 5:27 am

Hello .
This is my xml file :
Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<root>
        <interfaces>
                <eth0>
                        <description>WAN</description>
                        <ip>192.168.0.7</ip>
                        <netmask>255.255.255.255</netmask>
                        <mac>1111111</mac>
                        <speed></speed>
                </eth0>

                <eth1>
                        <description>LAN</description>
                        <ip>192.168.0.8</ip>
                        <netmask>255.255.255.0</netmask>
                        <mac>222222</mac>
                        <speed>200</speed>
                </eth1>
        </interfaces>
</root>


How can add new element to interfaces ? for example add <eth2> .
I use lxml module for reading xml file :

Code: Select all
from lxml import etree , objectify

tree = etree.parse('config.xml')
root = tree.getroot()

print etree.tostring(root,  pretty_print=True)
mah454
 
Posts: 1
Joined: Mon Jun 17, 2013 5:10 am

Re: python lxml add element

Postby hansn » Mon Jun 17, 2013 8:05 am

I'm not familiar with lxml, but this looks like what you want.
Code: Select all
>>> html = etree.Element("html")
>>> body = etree.SubElement(html, "body")       # The body tag is added inside of the html tag (i think)
>>> body.text = "TEXT"                                   # The string 'TEXT' is added inside the body tag

>>> etree.tostring(html)
b'<html><body>TEXT</body></html>'


If you have further questions, here are the docs: http://lxml.de/tutorial.html
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm


Return to General Coding Help

Who is online

Users browsing this forum: snippsat and 3 guests