Xslt 从当前位置查找包含特定节点的项
我需要解析由嵌套组中的组件组成的xml。结果将是js数组。我希望仅当嵌套级别中有组件时才创建组。 我可以使用以下方法搜索节点是否有组件:Xslt 从当前位置查找包含特定节点的项,xslt,Xslt,我需要解析由嵌套组中的组件组成的xml。结果将是js数组。我希望仅当嵌套级别中有组件时才创建组。 我可以使用以下方法搜索节点是否有组件: <xsl:if test="count(.//ModuleComponent) > 0"> 只有当当前位置的其他所有节点都有组件时,我才需要在数组元素之间加逗号。这是我不能做的。我需要搜索当前所有节点中是否有组件 这一行只适用于下一个兄弟姐妹,而不是所有兄弟姐妹 <xsl:if test="count(following-
<xsl:if test="count(.//ModuleComponent) > 0">
只有当当前位置的其他所有节点都有组件时,我才需要在数组元素之间加逗号。这是我不能做的。我需要搜索当前所有节点中是否有组件
这一行只适用于下一个兄弟姐妹,而不是所有兄弟姐妹
<xsl:if test="count(following-sibling::ModuleComponent) > 0">
我的样本是:
<xsl:text>[</xsl:text>
<!--create components of group-->
<xsl:for-each select="Module/Groups/Group">
<xsl:call-template name="GroupTemplate">
</xsl:call-template>
</xsl:for-each>
<xsl:text>]</xsl:text>
<xsl:template name="GroupTemplate">
<xsl:variable name="groupID" select="@ID"/>
<!-- create this group only if it has components deep inside -->
<xsl:if test="count(.//ModuleComponent) > 0">
{
id: <xsl:value-of select="$ID" />
...
group body
...
}
<xsl:if test="count(following-sibling::ModuleComponent) > 0"><xsl:text>,</xsl:text></xsl:if>
</xsl:if>
</xsl:template>
[
]
{
身份证件:
...
团体
...
}
,
示例xml是:
<Module>
<Groups>
<Group ID="1">
<Groups>
<Group ID="11">
<Component ID="c1"/>
</Group>
</Groups>
</Group>
<Group ID="2">
<Groups>
<Group ID="22">
</Group>
</Groups>
</Group>
<Group ID="3">
<Groups>
<Group ID="33">
<Component ID="c3"/>
</Group>
</Groups>
</Group>
</Groups>
</Module>
非常感谢您的任何想法或帮助。如果您想生成一个数组,您不必调用单独的模板。您可以将每个
的第一个更改为迭代//Component
并测试last()
位置:
<xsl:text>[</xsl:text>
<xsl:for-each select=".//Component">
{
id: <xsl:value-of select="@ID" />
...
component body
...
}
<xsl:if test="not(position() = last())"><xsl:text>,</xsl:text></xsl:if>
</xsl:for-each>
<xsl:text>]</xsl:text>
[
{
身份证件:
...
组件体
...
}
,
]
使其成为匹配的模板而不是调用的模板,并将“我是否包含任何模块组件
”逻辑移动到谓词中,而不是(如果
):
<xsl:text>[</xsl:text>
<xsl:apply-templates select="Module/Groups/Group[.//ModuleComponent]"/>
<xsl:text>]</xsl:text>
<xsl:template match="Group">
<xsl:if test="position() > 1">,</xsl:if>
{
id: <xsl:value-of select="@id" />
...
group body
...
}
</xsl:template>
[
]
,
{
身份证件:
...
团体
...
}
现在您只对至少有一个组件的组进行操作,position()
是该组在该列表中的位置,而不是在所有组的列表中,因此您只需在除第一个之外的所有组之前添加逗号。在源代码中没有ModuleComponent
。没有$ID
,并且XSLT文件不完整。请更正。谢谢你的回答。我在上面的帖子中犯了一个错误。更新此:。。。组件体。。。对此:。。。团体。。。这只是创建组。不是组件。组是嵌套的。并且只创建具有组件的组件。在组内使用另一个模板来创建组件。