Re: [xml-bindings]XSLT extension functions

On Mon, 10 Jun 2002, Gary Benson wrote:

> I've been trying to write some extension functions in python, and have a 
> few questions.

So I figured this out for myself in the end: read on...

> Firstly, I've been trying something like the example in
> | def f(ctx, str):
> |     return string.upper(str)
> | 
> | libxslt.registerExtModuleFunction("foo", "";, f)
> This works fine when I call it like in the example:
> | <xsl:value-of select="foo:foo('bar')"/>
> But, if I call it with something like:
> | <xsl:value-of select="foo:foo(@date)"/>
> Then instead of a string, the function gets passed a list of one 
> PyCObject.  What is this object, and how do I turn it into something I can 
> access?  I'm currently working around this by calling foo:foo(string(@date))
> but that's a little hacky...

Okay, so the PyCObjects are nodes.  You can turn them into xmlNode objects 

| def f(ctx, nodeset):
|     nodeset = map(lambda n: libxml2.xmlNode(_obj=n), nodeset)
|     ...

> Secondly, with this method I am only able to return strings (or, I guess, 
> numbers).  How would I go about returning a node set?  What would you 
> create the node set from, since you need a parent node to create a new 
> node?

Okay, so you need to get the insertion node of the output document and use 
that as the parent:

| def f(ctx, nodeset):
|     ...
|     pctxt = libxslt.xpathParserContext(_obj=ctx)
|     ctxt  = pctxt.context()
|     tctxt = ctxt.transformContext()
|     root  = tctxt.insertNode()

You then insert nodes (which appear in the output document):

|     node = root.newTextChild(None, "strong", "hello mum")

And finally, you return an empty string:

|     return ""

Don't know if this is a sensible thing to do, but it works :)

> Finally, is it possible to create an XSL thing instead of creating an 
> XPath function? So I could do something like:
> | <foo:foo select="@date">
> rather than using xsl:value-of.

I didn't work this out, but it's not important (to me) anymore...


[ gary inauspicious org ][ GnuPG 85A8F78B ][ ]

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]