提取索引处的特定节点,并使用参数指定索引来忽略其他节点



我希望能够仅提取一组节点中的第n个节点。

给定以下xml文件:

<?xml version="1.0"?>
<problem>
<header>This is a header</header>
<lines>
<line>This is the first line</line>
<line>This is the second line</line>
<line>This is the third line</line>
</lines>
</problem>

我怎么能只把第二行和所有其他元素一起传出去呢?换句话说,我希望这是输出:

<?xml version='1.0' ?>
<problem>
<header>This is a header</header>
<lines>
<line>This is the second line</line>    
</lines>
</problem>

我有一个样式表可以做我想做的事情,但前提是我要硬编码索引。此:

<?xml version='1.0'?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="index"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates  select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/problem/lines/line"/>
<xsl:template match="/problem/lines/line[2]">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>

生成的正是我想要的,但如果我试图通过将[2]替换为参数$index:来参数化索引

<?xml version='1.0'?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="index"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates  select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/problem/lines/line"/>
<xsl:template match="/problem/lines/line[$index]">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>

并将$index的值设置为2,我得到的是:

<?xml version='1.0' ?>
<problem>
<header>This is a header</header>
<lines>
<line>This is the first line</line>
<line>This is the second line</line>
<line>This is the third line</line>
</lines>
</problem>

所以我认为没有使用参数找到索引匹配的模板。

如何修复此问题,以便将参数用于索引?

我让它工作起来了;我需要将参数从字符串转换为整数。这起到了作用:

<?xml version='1.0'?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="index"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates  select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/problem/lines/line"/>
<xsl:template match="/problem/lines/line[number($index)]">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>

最新更新