gpt4 book ai didi

xslt - 我想在 apply-templates 不匹配时调用命名模板

转载 作者:行者123 更新时间:2023-12-02 07:41:28 26 4
gpt4 key购买 nike

这是我在生成 XSL-FO 的更复杂的 XSLT 1.0 样式表中遇到的匹配问题的一个简单示例。

给定此输入 XML,其中 <Library>可能包含零个或多个 <Item>节点,

<Library>
<Item type="magazine" title="Rum"/>
<Item type="book" title="Foo" author="Bar"/>
<Item type="book" title="Fib" author="Fub"/>
<Item type="magazine" title="Baz"/>
</Library>

还有这个 XSLT:

<xsl:template match="Library">
<xsl:apply-templates select="Item[@type='Magazine']/>
<!-- How to call "NoMagazines" from here? -->
<xsl:apply-templates select="Item[@type='Book']/>
<!-- How to call "NoBooks" from here? -->
</xsl:template>

<xsl:template match="Item[@type='book']">
<!-- do something with books -->
</xsl:template>

<xsl:template match="Item[@type='magazine']">
<!-- do something with magazines -->
</xsl:template>

<!-- how to call this template? -->
<xsl:template name="NoBooks">
Sorry, No Books!
</xsl:template>

<!-- how to call this template? -->
<xsl:template name="NoMagazines">
Sorry, No Magazines!
</xsl:template>

我想生成替代方案“对不起,不 [随便]!”来自 Library 的消息没有Item时的模板[whatever] 类型的节点。

到目前为止,我所做的唯一(丑陋的)解决方案是通过键入变量来选择子节点,测试变量,然后如果变量包含节点则应用模板,或者调用适当的“不匹配” named template 如果变量为空(我假设 test="$foo"如果没有选择节点将返回 false,我还没有尝试过):

<xsl:template match="Library">
<xsl:variable name="books" select="Items[@type='book']"/>

<xsl:choose>
<xsl:when test="$books">
<xsl:apply-templates select="$books"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="NoBooks"/>
</xsl:otherwise>
</xsl:choose>

<xsl:variable name="magazines" select="Items[@type='magazine']"/>

<xsl:choose>
<xsl:when test="$magazines">
<xsl:apply-templates select="$magazines"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="NoMagazines"/>
</xsl:otherwise>
</xsl:choose>

</xsl:template>

我认为这一定是一个 XSLT 设计模式(在 GoF 意义上),但我在网上找不到示例。非常欢迎任何建议!

最佳答案

也许像这样,作为 Dimitre 解决方案的变体:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my"
>
<xsl:output method="text"/>

<my:errorObjects>
<noItem type="book">No Books</noItem>
<noItem type="magazine">No Magazines</noItem>
</my:errorObjects>

<xsl:variable name="vErrorObjects" select=
"document('')/*/my:errorObjects"/>


<xsl:template match="/*">
<xsl:apply-templates select="(.|$vErrorObjects)/*[@type='magazine']/>
<xsl:apply-templates select="(.|$vErrorObjects)/*[@type='book']"/>
</xsl:template>

<xsl:template match="Item">
<xsl:value-of select="concat('&#xA;Type: ', @type, ', title: ', @title)"/>
</xsl:template>

<xsl:template match="noItem">
<xsl:if test="last() = 1">
Sorry: <xsl:value-of select="."/>
</xsl:if>
</xsl:template>

</xsl:stylesheet>

关于xslt - 我想在 apply-templates 不匹配时调用命名模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10608579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com