Representing xml through a single class

Posted by Charles on Stack Overflow See other posts from Stack Overflow or by Charles
Published on 2010-03-12T04:10:20Z Indexed on 2010/03/12 4:17 UTC
Read the original article Hit count: 245

Filed under:
|
|

I am trying to abstract away the difficulties of configuring an application that we use. This application takes a xml configuration file and it can be a bit bothersome to manually edit this file, especially when we are trying to setup some automatic testing scenarios.

I am finding that reading xml is nice, pretty easy, you get a network of element nodes that you can just go through and build your structures quite nicely. However I am slowly finding that the reverse is not quite so nice. I want to be able to build a xml configuration file through a single easy to use interface and because xml is composed of a system of nodes I am having a lot of struggle trying to maintain the 'easy' part.

Does anyone know of any examples or samples that easily and intuitively build xml files without declaring a bunch of element type classes and expect the user to build the network themselves?

For example if my desired xml output is like so

<cook version="1.1">
    <recipe name="chocolate chip cookie">
        <ingredients>
            <ingredient name="flour" amount="2" units="cups"/>
            <ingredient name="eggs" amount="2" units="" />
            <ingredient name="cooking chocolate" amount="5" units="cups" />
        </ingredients>
        <directions>
            <direction name="step 1">Preheat oven</direction>
            <direction name="step 2">Mix flour, egg, and chocolate</direction>
            <direction name="step 2">bake</direction>
        </directions>
    </recipe>
    <recipe name="hot dog">
    ...

How would I go about designing a class to build that network of elements and make one easy to use interface for creating recipes?

Right now I have a recipe object, an ingredient object, and a direction object. The user must make each one, set the attributes in the class and attach them to the root object which assembles the xml elements and outputs the formatted xml. Its not very pretty and I just know there has to be a better way.

I am using python so bonus points for pythonic solutions

© Stack Overflow or respective owner

Related posts about Xml

Related posts about python