我有一些XML需要将父节点添加到node1,node2,node3等。然后我还需要与其他节点分组:
原始XML:
<parentnode>
<childnode attribute="option.a.b.1">
</childnode>
<childnode attribute="option.a.b.2">
</childnode>
<childnode attribute="option.a.b.1">
</childnode>
<childnode attribute="option.a.b.2">
</childnode>
<childnode attribute="option.a.b.3">
</childnode>
<childnode attribute="option.a.b.1">
</childnode>
<childnode attribute="option.a.b.2">
</childnode>
</parentnode>
所需的XML:
<parentnode>
<row0>
<childnode attribute="option.a.b.1">
</childnode>
<childnode attribute="option.a.b.2">
</childnode>
</row0>
<row1>
<childnode attribute="option.a.b.1">
</childnode>
<childnode attribute="option.a.b.2">
</childnode>
<childnode attribute="option.a.b.3">
</childnode>
</row1>
<row2>
<childnode attribute="option.a.b.1">
</childnode>
<childnode attribute="option.a.b.2">
</childnode>
</row2>
</parentnode>
option.a.b。* * *可以是任何数字我只需要它每次出现option.a.b.1时开始一个新行。我甚至不确定这是否可以在XSLT中使用?
答案 0 :(得分:1)
假设您可以使用像Saxon 9或XmlPrime或AltovaXML这样的XSLT 2.0处理器
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="parentnode">
<xsl:copy>
<xsl:for-each-group select="childnode" group-starting-with="childnode[@attribute = 'option.a.b.1']">
<row>
<xsl:copy-of select="current-group()"/>
</row>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
</xsl:transform>
我故意不对行元素进行编号,因为在我的视图中导致格式不佳,如果你真的需要那么使用
<xsl:template match="parentnode">
<xsl:copy>
<xsl:for-each-group select="childnode" group-starting-with="childnode[@attribute = 'option.a.b.1']">
<xsl:element name="row{position() - 1}">
<xsl:copy-of select="current-group()"/>
</xsl:element>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
答案 1 :(得分:1)
每次出现option.a.b.1时我只需要它开始一个新行。我&#39;米 甚至不确定这是否可以在XSLT中使用?
XSLT - 甚至XSLT 1.0 - 是一种图灵完备语言,所以是的, 是可能的。如果您使用的是XSLT 1.0,请尝试:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:key name="k" match="childnode[not(@attribute='option.a.b.1')]" use="generate-id(preceding-sibling::childnode[@attribute='option.a.b.1'][1])" />
<xsl:template match="/parentnode">
<xsl:copy>
<xsl:for-each select="childnode[@attribute='option.a.b.1']">
<xsl:element name="row{position()-1}">
<xsl:copy-of select=". | key('k', generate-id())"/>
</xsl:element>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
注意:你可以通过调整我在这里给出的答案来解决这个问题:https://stackoverflow.com/a/26397156/3016153