英文:
XSLT grouping via for-each-group and group-starting-with?
问题
我正在尝试为下面的示例创建分组。元素 'ques' 和紧随其后的兄弟元素 'p' 被放置在 'group' 元素内部。
输入的XML
<root>
<title>Title</title>
<p>para</p>
<ques>Ques</ques>
<p>aaaa</p>
<fig>aaa</fig>
<box>box</box>
<ques>Ques</ques>
<p>aaaa</p>
<p>bbbb</p>
</root>
XSLT 代码
<xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>
<xsl:template match="root">
<xsl:copy>
<xsl:for-each-group select="*" group-starting-with="ques">
<group>
<xsl:copy-of select="current-group()"/>
</group>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
期望的输出
<root>
<title>Title</title>
<p>para</p>
<group>
<ques>Ques</ques>
<p>aaaa</p>
</group>
<fig>aaa</fig>
<box>box</box>
<group>
<ques>Ques</ques>
<p>aaaa</p>
<p>bbbb</p>
</group>
</root>
链接: XSLT Fiddle
英文:
I'm trying to create group for below example. Element 'ques' and just following-sibling::p make inside the 'group' element<br/>
Input XML
<root>
<title>Title</title>
<p>para</p>
<ques>Ques</ques>
<p>aaaa</p>
<fig>aaa</fig>
<box>box</box>
<ques>Ques</ques>
<p>aaaa</p>
<p>bbbb</p>
</root>
XSLT Code:
<xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>
<xsl:template match="root">
<xsl:copy>
<xsl:for-each-group select="*" group-starting-with="ques">
<group>
<xsl:copy-of select="current-group()"/>
</group>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
Expected Output:
<root>
<title>Title</title>
<p>para</p>
<group>
<ques>Ques</ques>
<p>para</p>
</group>
<fig>fig</fig>
<box>box</box>
<group>
<ques>Ques</ques>
<p>para</p>
<p>para</p>
</group>
</root>
Link:
<https://xsltfiddle.liberty-development.net/6qVQdo6>
答案1
得分: 3
尝试可能是这样的:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/root">
<xsl:copy>
<xsl:for-each-group select="*" group-starting-with="ques">
<xsl:for-each-group select="current-group()" group-adjacent="self::ques or self::p">
<xsl:choose>
<xsl:when test="self::ques">
<group>
<xsl:copy-of select="current-group()"/>
</group>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="current-group()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
英文:
Try perhaps something like:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/root">
<xsl:copy>
<xsl:for-each-group select="*" group-starting-with="ques">
<xsl:for-each-group select="current-group()" group-adjacent="self::ques or self::p">
<xsl:choose>
<xsl:when test="self::ques">
<group>
<xsl:copy-of select="current-group()"/>
</group>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="current-group()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论