有谁能帮忙找出解决办法吗?
需求-使用XSLT1.0
我的xml结构类似于
<w:p xmlns:w="http://foo.com">
<w:r>run1</w:r>
<w:r>run2</w:r>
<w:r>runn3</w:r>
<w:p>
<w:r>para1</w:r>
</w:p>
<w:p>
<w:r>para2</w:r>
</w:p>
<w:r>run4 - after para2</w:r>
<w:r>run5- after para2</w:r>
<w:p>
<w:r>last para</w:r>
</w:p>
</w:p>使用XSLT1.0,我希望输出如下:
<root>
<w:p>
<w:r>run1</w:r>
<w:r>run2</w:r>
<w:r>runn3</w:r>
</w:p>
<w:p>
<w:r>para1</w:r>
</w:p>
<w:p>
<w:r>para2</w:r>
</w:p>
<w:p>
<w:r>run4 - after para2</w:r>
<w:r>run5- after para2</w:r>
</w:p>
<w:p>
<w:r>last para</w:r>
</w:p>
</root>基本上我想按顺序分组
我试过的XSLt:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0" xmlns:w="http://foo.com" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:template match="/">
<root>
<!--<xsl:for-each select="w:p/*">
<xsl:choose>
<xsl:when test="name()='w:r'">
<w:p>
<xsl:copy-of select="."/>
</w:p>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>-->
<xsl:apply-templates select="w:r |w:p"/>
</root>
</xsl:template>
<xsl:template match="w:r">
<w:p>
<xsl:copy-of select="."/>
</w:p>
</xsl:template>
<xsl:template match="w:p/w:p">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>我正在获得的产出:
<?xml version="1.0" encoding="UTF-16"?>
<root xmlns:w="http://foo.com" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<w:p>
<w:r>run1</w:r>
</w:p>
<w:p>
<w:r>run2</w:r>
</w:p>
<w:p>
<w:r>runn3</w:r>
</w:p>
<w:p>
<w:r>para1</w:r>
</w:p>
<w:p>
<w:r>para2</w:r>
</w:p>
<w:p>
<w:r>run4 - after para2</w:r>
</w:p>
<w:p>
<w:r>run5- after para2</w:r>
</w:p>
<w:p>
<w:r>last para</w:r>
</w:p>
</root>发布于 2013-10-04 13:42:40
在这里,我将完全忽略现有的w:p元素。最终,您需要的是一个名为root的根元素,它包含原始源中相邻w:r元素每次运行的一个w:p元素,而不管这些w:r元素以前是否包装在w:p中。您可以使用一种我称之为同级递归的技术来处理这个问题--从一个模板开始,该模板会激发每个组中的第一个w:r,然后让它立即恢复到其后续的同级,直到您碰到一个不是另一个w:r的模板。
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0" xmlns:w="http://foo.com">
<xsl:template match="/">
<root>
<xsl:apply-templates mode="group"
select=".//w:r[not(preceding-sibling::*[1][self::w:r])]" />
</root>
</xsl:template>
<xsl:template match="w:r" mode="group">
<w:p>
<xsl:apply-templates select="." /><!-- applies non-"group" templates -->
</w:p>
</xsl:template>
<xsl:template match="w:r">
<xsl:copy-of select="."/>
<xsl:apply-templates select="following-sibling::*[1][self::w:r]" />
</xsl:template>
</xsl:stylesheet>魔力在于select表达式。
.//w:r[not(preceding-sibling::*[1][self::w:r])]选择不立即跟随另一个w:r的所有w:r元素(即每个连续运行中的第一个)。
following-sibling::*[1][self::w:r]选择当前元素的紧跟同级元素,但前提是它是w:r。如果没有后续的同级元素,或者存在一个但是不是w:r的元素,表达式将不会选择任何内容。
https://stackoverflow.com/questions/19178669
复制相似问题