Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QXmlQuery - passing parameter to XSLT

Tags:

c++

xslt

qt

Sample XSLT

<?xml version="1.0"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes" encoding="UTF-8"/>
<xsl:param name="my-param" select="'none'"/>

<xsl:template match="sample">
  <html><body><p>
    parameter: <xsl:value-of select="$my-param"/>
  </p></body></html>
</xsl:template>

Sample XML:

<sample/>

Using xmlpatterns like so:

xmlpatterns sample.xsl sample.xml -param my-param=funky

I can make the HTML output read:

<html><body><p>
   parameter: funky</p></body></html>

Brilliant!

Q: How do I pass my-param to my XSLT using QXmlQuery?

I suspect it must be one of the bindVariable() overloads, but none seem a match for a simple string parameter.

Additional information in case it matters: We are still using Qt4.7 at work. But having had a quick look on the internet, the public interface for QXmlQuery seems no different in Qt 5.x

EDIT

What I have so far:

QString output;

QXmlQuery query(QXmlQuery::XSLT20);
query.setFocus(QUrl(input_xml));
query.setQuery(QUrl::fromLocalFile(":/sample.xsl"));
query.evaluateTo(&output);

I use QXmlQuery::XSLT20 because it gives me the least headaches even though my XSLT is targeted at version 1.0 (just in case this has you confused)

like image 488
iwarv Avatar asked Nov 25 '25 20:11

iwarv


1 Answers

You can use the bindVariable method effectively, but it depends on your XSLT, though.

If you have

<xsl:param name="my-param" select="$qt-var"/>

and later

parameter: <xsl:value-of select="$my-param"/>

This code will work as expected (please notice that variables must be bound before setting the query):

QXmlQuery query(QXmlQuery::XSLT20);
query.bindVariable("qt-var", QVariant("my value"));
query.setFocus(input_xml);
query.setQuery(xslt);
query.evaluateTo(&output);

If you omit the xsl:param declaration, and just have

parameter: <xsl:value-of select="$qt-var"/>

it will work as well.

You can still use xmlpatterns, as long as the qt-var is passed in:

xmlpatterns sample.xsl sample.xml -param qt-var=qtfunky
like image 180
p-a-o-l-o Avatar answered Nov 27 '25 10:11

p-a-o-l-o



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!