如何在xslt中将参数用作XPath? [英] How to use a parameter in a xslt as a XPath?

查看:92
本文介绍了如何在xslt中将参数用作XPath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将元素添加到xml文档中,并希望将元素的路径作为参数传递.

I'd like to add an element to a xml document and I'd like to pass as a parameter the path to the element.

sample.xml文件:

sample.xml file:

<?xml version="1.0"?>
<stuff>
  <element1>
    <foo>2</foo>
<bar/>
  </element1>
  <element2>
<subelement/>
<bar/>
   </element2>
   <element1>
     <foo/>
 <bar/>
   </element1>
 </stuff>

使用:

xalan.exe -p myparam "element1" sample.xml addelement.xslt

我想要以下结果:

<?xml version="1.0"?>
<stuff>
  <element1>
    <foo>2</foo>
    <bar/>
    <addedElement/>
  </element1>
  <element2>
<subelement/>
<bar/>
   </element2>
   <element1>
     <foo/>
 <bar/>
     <addedElement/>
   </element1>
 </stuff>

当对路径进行硬编码时,我设法编写了addelement.xslt,但是当我尝试使用 我得到的match属性中的参数myparam:

I've manage to write addelement.xslt, when hardcoding the path it works, but when I try to use parameter myparam in the match attribute I get:

XPathParserException: A node test was expected.
pattern = '$myparam/*[last()]' Remaining tokens are:  ('$' 'myparam' '/' '*' '[' 'last' '(' ')' ']') (addelement.xslt, line 12, column 42)

addelement.xslt

addelement.xslt

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

<xsl:template match="element1/*[last()]">
    <xsl:copy-of select="."/>
<addedElement></addedElement>
</xsl:template>

</xsl:stylesheet>

addelement.xslt替换为硬编码路径

addelement.xslt with hardcoded path replaced

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:param name="myparam"/>

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

<xsl:template match="$myparam/*[last()]">
    <xsl:copy-of select="."/>
<addedElement></addedElement>
</xsl:template>

</xsl:stylesheet>

感谢您的帮助

推荐答案

我认为您不能像您编码的那样在匹配模板中使用变量/参数.即使这样也不行

I don't think you can use variables/paramaters in matching templates like you have coded. Even this doesn't work

<xsl:template match="*[name()=$myparam]/*[last()]">

相反,请尝试将第一个匹配的模板更改为如下所示,以使参数检查位于模板代码内,而不是match语句的一部分.

Instead, try changing the first matching template to as follows, so that the parameter check is inside the template code, not as part of the match statement.

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:if test="local-name() = $myparam">
            <addedElement/>
        </xsl:if>
    </xsl:copy>
</xsl:template>

这篇关于如何在xslt中将参数用作XPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆