"I have a mind like a steel... uh... thingy." Patrick Logan's weblog.

Search This Blog

Tuesday, June 17, 2003

Jython and JXPath

I recently started using JXPath, an XPath implementation for multiple underlying data models in Java. It works out of the box for DOM, JDOM, java.util.Map, servlet contexts, and Java Beans. Probably others.

I wanted to use XPath to query Jython objects. The really cool thing is the amount of code it takes to do so. It's so short I include it right here...

from java.lang import String
from org.apache.commons.jxpath import JXPathIntrospector
from org.apache.commons.jxpath import DynamicPropertyHandler
import jarray

class JythonPropertyHandler (DynamicPropertyHandler):
    def getPropertyNames (self, py_object):
        keys = py_object.__dict__.keys()
        return jarray.array(keys, String)
    def getProperty(self, py_object, property):
        if py_object.__dict__.has_key(property):
            return py_object.__dict__[property]
            return None
    def setProperty(self, py_object, property, value):
        py_object.__dict__[property] = value

def registerJythonPropertyHandler():
    JXPathIntrospector.registerDynamicClass(PyInstance, JythonPropertyHandler)

And so...

>>> context = JXPathContext.newContext(some_object)
>>> context.getValue("frob[abc > 1]")
<__main__.Foo instance at 3278971>

No comments:

Blog Archive

About Me

Portland, Oregon, United States
I'm usually writing from my favorite location on the planet, the pacific northwest of the u.s. I write for myself only and unless otherwise specified my posts here should not be taken as representing an official position of my employer. Contact me at my gee mail account, username patrickdlogan.