XSLT CallTemplate ForEach XML

佐手、 提交于 2019-12-12 03:39:26

问题


I need a little XSLT help. Couldn't figure out why the actual output is different from my expected output. Any help much appreciated!

XML

<?xml version="1.0"?>
<a>
  <b c="d"/>
  <b c="d"/>
  <b c="d"/>
</a>

XSL

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template name="foo">
        <xsl:param name="content"></xsl:param>
        <xsl:value-of select="$content"></xsl:value-of>
    </xsl:template>

    <xsl:template match="/">
        <xsl:call-template name="foo">
            <xsl:with-param name="content">
                <xsl:for-each select="a/b">
                    <e>
                        <xsl:value-of select="@c" />
                    </e>
                </xsl:for-each>
            </xsl:with-param>
        </xsl:call-template>
    </xsl:template>

Actual Output

<?xml version="1.0"?>
ddd

Desired Output

<?xml version="1.0"?>
<e>d</e>
<e>d</e>
<e>d</e>

Note: Calling the template is mandatory. In my situation the template does more with extension functions.


回答1:


Contrary to what ABach says, your xsl:param is fine. The only thing you need to change is your xsl:value-of. It should be a xsl:copy-of:

<xsl:template name="foo">
    <xsl:param name="content"/>
    <xsl:copy-of select="$content"/>
</xsl:template>



回答2:


You're very close; you've just mixed up relative positioning and correct parameter usage within templates. Here's a slightly revised answer.

When this XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
  <xsl:output omit-xml-declaration="no" indent="yes" />
  <xsl:strip-space elements="*" />

  <xsl:template name="foo">
    <xsl:param name="pContent" />
    <xsl:for-each select="$pContent">
      <e>
        <xsl:value-of select="@c" />
      </e>
    </xsl:for-each>
  </xsl:template>

  <xsl:template match="/*">
    <xsl:call-template name="foo">
      <xsl:with-param name="pContent" select="*" />
    </xsl:call-template>
  </xsl:template>

</xsl:stylesheet>

...is applied to the original XML:

<?xml version="1.0"?>
<a>
  <b c="d" />
  <b c="d" />
  <b c="d" />
</a>

...the desired result is produced:

<?xml version="1.0"?>
<e>d</e>
<e>d</e>
<e>d</e>

In particular, notice the correct usage of <xsl:param> to include nodes based on their relative position. In your case, you are telling the XSLT parser to output the text values of the parameter that you're passing, rather than altering the nodes' contents in the way you want.



来源:https://stackoverflow.com/questions/13096832/xslt-calltemplate-foreach-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!