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 : http://dpaste.com/55552/
This is the xsl template : http://dpaste.com/55553/

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

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
<xsl:output indent="yes"/>
<xsl:template match="messages">
<GenericItems><xsl:text>&#10;</xsl:text>
...

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 : http://dpaste.com/55554/

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)
style.freeStylesheet()
doc.freeDoc()
result.freeDoc()

The XSLT would then be, for example:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>

  <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 }">
      <Earth/>
      <Plants/>
      <Animals/>
      <Humans/>
    </xsl:element>
  </xsl:template>

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

</xsl:stylesheet>

Michael Ludwig


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