rules from an xml file

Stefan Behnel stefan.behnel-n05pAM at web.de
Mon Sep 24 14:08:20 CEST 2007


jonny wrote:
> I have a python code that manages some parameters using some variable
> rules that may change from day to day. I'd like that the code will
> self-modify according to rules parsed from a xml file:
> 
> example:
> 
> <rules>
>    <rule01>
>       <if>
> 		<or>
> 			<lessthan par_1="glicemyAtMorning" par_2="80"/>
> 			<lessthan par_1="glicemyAtNight" par_2="80"/>
> 			<and>
> 				<greaterthan par_1="glicemyAtMorning" par_2="0"/>
> 				<or>
> 					<equalto par_1="urine" par_2="0"/>
> 					<equalto par_1="urine" par_2="+/-"/>
> 					<equalto par_1="urine" par_2="+"/>
> 				</or>
> 			</and>
> 		</or>
> 	</if>
>         <then>
>            <sendmessage>Something is wrong!</sendmessage>
>         </then>
>    </rule01>
>    <rule02> ...  </rule02>
>    <rule03> ...   </rule03>
> </rules>
> 
> Due to the fact that rules may change, I have to manage the python
> program, parsing the whole xml file, and self-modify the python code
> according to these variable rules.
> How can I do?

A beautiful solution could be to implement a namespace for these elements in
lxml.etree (even if it's not an XML namespace with a URI). You would give each
of the elements its own subclass of lxml.etree.BaseElement, maybe split into
rule elements and expression elements, and then give each of them an
evaluate() method that returns the result of the evaluation, such as

    def evaluate(self):
        for child in self:
            if child.evaluate():
                return True
        return False

for the "or" element or

    def evaluate(self):
        if self[0].evaluate():
            return self.getnext().evaluate()
        else:
            return self.getnext().getnext().evaluate()

for an "if-then-else" statement as in your example above (plus special casing
if "then" or "else" are not there).

Then you define a mapping from the tag names to your element classes and let
lxml.etree instantiate the decision tree for you.

Here is the documentation on this feature:
http://codespeak.net/lxml/dev/element_classes.html
http://codespeak.net/lxml/dev/element_classes.html#id1

Especially these two class lookup schemes might be handy:
http://codespeak.net/lxml/dev/element_classes.html#custom-element-class-lookup
http://codespeak.net/lxml/dev/element_classes.html#namespace-class-lookup

And here is an example:
http://codespeak.net/svn/lxml/trunk/src/lxml/html/__init__.py

Have fun,
Stefan



More information about the Python-list mailing list