You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用QXmlQuery向XSLT传递字符串参数?

用QXmlQuery向XSLT传递字符串参数的解决方案

先回顾下你给出的示例文件和命令:

示例文件

示例XSLT(sample.xsl)

<?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>
</xsl:stylesheet>

示例XML(sample.xml)

<sample/>

你之前用xmlpatterns工具执行的命令:

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

最终生成的HTML输出:

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

核心问题解决:用QXmlQuery绑定参数

你猜测需要用bindVariable()的重载是对的,只是可能没注意到它可以直接处理字符串——Qt会自动把字符串隐式转换为QVariant,完全适配这个方法。

修改你现有的代码,加上参数绑定步骤即可:

QString output;
QXmlQuery query(QXmlQuery::XSLT20);

// 关键步骤:绑定XSLT中定义的my-param参数
query.bindVariable("my-param", QString("funky"));

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

额外说明

  • 参数绑定的顺序比较灵活,放在setQuery前后都可以,但建议放在setQuery之后、evaluateTo之前,逻辑上更连贯。
  • 你使用的是Qt4.7,而QXmlQuery的这个bindVariable接口在Qt5.x中没有变化,所以这个写法在两个版本都能正常运行。
  • 虽然你的XSLT是1.0版本,但用QXmlQuery::XSLT20模式完全没问题,Qt的XSLT处理器兼容1.0语法,不用担心版本冲突。

内容的提问来源于stack exchange,提问作者iwarv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:45:52