I have put some xml data in a file the python code below and have been trying to figure out how to get the data from the file add another "person" and then save to the same file again.

from lxml import etree
from lxml.builder import ElementMaker


E = ElementMaker()

DOC = E.doc
PERSON = E.activity
TITLE = E.title
DESC = E.desc
IDNO = E.idno

def NAME(*args):
    return {"name":' '.join(args)}


thing = DOC (
    PERSON( NAME("John"),
    DESC ("germedabob"),
    IDNO ("2")
    )
    )

filename = "xmltestthing.xml"
FILE = open(filename,"w")
FILE.writelines(etree.tostring(thing, pretty_print=True))
FILE.close()

This is what I have got so far, I can't work out how to add anything to it and save it again.

from lxml import etree

file = "xmltestthing.xml"
thing1 = etree.parse(file)
print(etree.tostring(thing1, pretty_print=True))

That outputs:

<doc>
  <person name="John">
    <desc>germedabob</desc>
    <idno>2</idno>
  </person>
</doc>

Thanks

Recommended Answers

All 5 Replies

I have been for a while now, it does not really deal with files, unless I am missing something completely

I managed adding an element this way

from lxml import etree
from lxml.builder import ElementMaker


E = ElementMaker()

DOC = E.doc
PERSON = E.activity
TITLE = E.title
DESC = E.desc
IDNO = E.idno
def NAME(*args):
    return {"name":' '.join(args)}

file = "xmltestthing.xml"
parser = etree.XMLParser(remove_blank_text=True) # see http://codespeak.net/lxml/FAQ.html#parsing-and-serialisation
thing1 = etree.parse(file, parser)

person = PERSON( NAME("Dani"),
    DESC ("the queen"),
    IDNO ("5")
    )

doc = thing1.getroot()
doc[-1].addnext(person)
print(etree.tostring(doc, pretty_print=True))

""" My output -->
<doc>
  <activity name="John">
    <desc>germedabob</desc>
    <idno>2</idno>
  </activity>
  <activity name="Dani">
    <desc>the queen</desc>
    <idno>5</idno>
  </activity>
</doc>
"""
commented: Thanks +2

Thanks a lot man. I just needed a starting point in code as I couldn't understand the "Tutorial" thing on it. Sorry about the mix-up in outputs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.