Re: [xslt] Passing variables from python to an xslt template

Francisco Rivas schrieb:
Hi, I am writing a litle python program which apply a xslt template to
a xml file additionally I need to pass a veriable to the template I
know using applyStylesheet method I can pass a dictionary but I do not
know how to use it in the template.

This is my code :
This is the xsl template :

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
<xsl:output indent="yes"/>
<xsl:template match="messages">

Don't clutter your stylesheet with literal text to achieve what can be
achieved declaratively using <xsl:output indent="yes"/>, as above. Or
should be achieved; maybe the Python bindings do not work as expected.
Still, I wouldn't waste time on this. If you need indentation for
readability, you can get it using "xmllint --format" as needed.

This is the xml file :

I saw the xsl:param, xsl:with-param but it is not what I want.

Yes it is exactly what you want.

So I want to add a new subitem but not from the xml I want to pass it
from my python code, that is what i want, does anybody know how to do
that?... any kind of help will be appreciatte, thanks in advance and
best regards :D

I've never used the Python interface to LibXSLT, so I don't know if it's
possible to construct a node in code and then pass it as a parameter to
the stylesheet. Anyway, you're passing only a string. Or, trying to. In
fact, and counter-intuitively so, you have to quote the string as in
the following corrected program:

import libxml2
import libxslt

project = "'evolution'" # remember to quote string like this
dict = {'source': project}

styledoc = libxml2.parseFile("xslt2.xsl")
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.parseFile("xslt.xml")
result = style.applyStylesheet(doc, dict)
style.saveResultToFilename("xslt.out", result, 0)

The XSLT would then be, for example:

<xsl:stylesheet version="1.0"

  <xsl:strip-space elements="*"/><!-- strip space on input -->
  <xsl:output indent="yes"/><!-- indent output -->

  <!-- top-level parameter -->
  <xsl:param name="source" select="'creation'"/>

  <xsl:template match="messages">
    <xsl:apply-templates select="*"/>
    <xsl:element name="{ $source }">

  <xsl:template match="@*|node()">
      <xsl:apply-templates select="@*|node()"/>


Michael Ludwig

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