如何在模板中迭代xsl中的变量?

时间:2016-09-20 14:44:53

标签: xml xslt xslt-1.0

我想设置一个变量,其中包含我想要从文档中排除的节点。我的理由是我希望非编码器能够简单地从xml文档中删除内容。

我的XML看起来像这样:

<?xml version="1.0" encoding="ISO-8859-1"?>
<document>
   <content name="location">New York</content>
   <content name="thing">Car</content>
   <content name="location">Baltimore</content>
</document>

我的XSL:

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

<xsl:variable name='exclude'>
    <content name="location">New York</content>
    <content name="location">Baltimore</content>
</xsl:variable>

<xsl:template match="content">
<!--The problem is here. 
<xsl:for-each select="?iterate?">
  <xsl:if test="not(?If a match isn't found, copy?)">
  <xsl:copy-of select="." />
  </xsl:if>
</xsl:for-each>
-->
</xsl:template>

转换后,文档应如下所示:

<document>
       <content name="thing">Car</content>
 </document>

我的主要问题是我无法弄清楚如何在for-each和模板中的节点中处理节点以进行比较。

1 个答案:

答案 0 :(得分:1)

这里的问题不是如何迭代,而是你的变量是结果树片段而不是节点集的事实。为避免此问题,您可以使用内部元素而不是变量:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="http://example.com/my"
extension-element-prefixes="my">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<my:exclude>
    <content name="location">New York</content>
    <content name="location">Baltimore</content>
</my:exclude>

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

<!-- exclude listed nodes -->
<xsl:template match="content[document('')/xsl:stylesheet/my:exclude/content[. = current() and @name = current()/@name]]"/>

</xsl:stylesheet>

加了:

要在开始时使用变量,您必须执行以下操作:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:variable name="exclude">
    <content name="location">New York</content>
    <content name="location">Baltimore</content>
</xsl:variable>

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

<xsl:template match="content">
    <xsl:if test="not(exsl:node-set($exclude)/content[. = current() and @name = current()/@name])">
        <xsl:copy-of select="."/>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>
相关问题