lxml objectify and Working with XML Tag Containing Periods
In reccent years, I have been working on automating Jenkin’s config XML files using Python and the lxml package.
However, one sub-topic I’ve never really learned how to do with Python is when you need to create or parse an XML tag that contains periods.
For example, Jenkin’s config files are notorious for having tags named like this: <hudson.triggers.TimerTrigger>
The way to get the value of a tag that contains periods is to use lxml’s objectify’s __getattr__() method and pass in the strangely named tag name:
For example:
But what do you do if you need to create a tag that contains periods in its name?
I wanted to enable the Build Periodically function in Jenkins programmatically. There are several tags and sub-tags that contain periods that I would need to create if I wanted to turn this feature on in a Jenkins job.
To do it successfully, you need to use __setattr__()
!
Here’s an example:
This example demonstrates how to use Python exception handling to create all the XML tags and sub-tags effectively and how to set the new tag to a value.
If the code is hard to read, you can get it in this public GitHub Gist.
Hopefully, you have found this mini-tutorial helpful and will be able to use it yourself someday!