2

I need to write a bunch of elements in an xml file and every couple of elements should be empty so in order to make the code a bit more compact i thought I'd make a function that writes out the empty elements. Of course I can't make a code that looks like this:

def makeOne():
   table=etree.SubElement(tables,'table')
   values = etree.SubElement(table,'values')

and call it later in the function that does the actual input of values because as much as I gathered the file I'm working with isn't loaded inside of that function. I might be wrong. I didn't do much Python so I have no idea if there's a more elegant way of handling this. For clarity this is what i had in mind.

def writeVals():
   tree = etree.parse('singleprog') 
   root = tree.getroot()
   tables = etree.SubElement(korjen[0], 'tables')
   makeOne()

I tihnk it's clear what I want to see happen here, the thing is I can't just put the two subelements in the writeVals() function because i need to use that code some 30 times at random places.

2
  • 2
    Can you pass tables as a parameter to makeOne? Commented May 1, 2017 at 13:01
  • Jesus, yes. Thanks Tom! Silly how I can't see things some time.. makeOne(tables) works like a charm. Commented May 1, 2017 at 14:00

1 Answer 1

1

That's not really answer the question but alternatively but you can use lxml library and it's wonderful E factory method:

from lxml import etree
from lxml.builder import E

table = E.table(E.values)

etree.dump(table)

You'll get:

<table>
  <values/>
</table>

To go further:

table = E.table(
    E.values("one"),
    E.values("two"),
    E.values("there"),
)

etree.dump(table)

You'll get:

<table>
  <values>one</values>
  <values>two</values>
  <values>there</values>
</table>

Introduction to lxml:

The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API. The latest release works with all CPython versions from 2.6 to 3.6. See the introduction for more information about background and goals of the lxml project. Some common questions are answered in the FAQ.

Sign up to request clarification or add additional context in comments.

2 Comments

For some reason I told myself I'd do this without using lxml but i'll have to think about implementing it as it would seem. Can it be used interchangeably with ElementTree? Also, I realized my problem was more with using functions than ET.
See Introduction to lxml:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.