XSLT:在空节点之间计数
XSLT: counting between empty nodes
给出如下XML(不知道有多少个空的<milestone>
元素):
<milestone n="a"/>
<seg>bla</seg>
<seg>bla</seg>
<milestone n="b"/>
<seg>bla</seg>
<seg>bla</seg>
需要转换为
<milestone n="a"/>
<seg n="1">bla</seg>
<seg n="2">bla</seg>
<milestone n="b"/>
<seg n="1">bla</seg>
<seg n="2">bla</seg>
我碰到一个空元素后如何重新开始计数?
感谢您的帮助!
请尝试以下解决方案
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs" version="2.0">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="seg">
<xsl:variable name="counter">
<xsl:number from="milestone" level="any"/>
</xsl:variable>
<seg>
<xsl:attribute name="n">
<xsl:value-of select="$counter"/>
</xsl:attribute>
</seg>
</xsl:template>
</xsl:stylesheet>
给出如下XML(不知道有多少个空的<milestone>
元素):
<milestone n="a"/>
<seg>bla</seg>
<seg>bla</seg>
<milestone n="b"/>
<seg>bla</seg>
<seg>bla</seg>
需要转换为
<milestone n="a"/>
<seg n="1">bla</seg>
<seg n="2">bla</seg>
<milestone n="b"/>
<seg n="1">bla</seg>
<seg n="2">bla</seg>
我碰到一个空元素后如何重新开始计数?
感谢您的帮助!
请尝试以下解决方案
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs" version="2.0">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="seg">
<xsl:variable name="counter">
<xsl:number from="milestone" level="any"/>
</xsl:variable>
<seg>
<xsl:attribute name="n">
<xsl:value-of select="$counter"/>
</xsl:attribute>
</seg>
</xsl:template>
</xsl:stylesheet>