我有TEI (文本编码倡议)文档,其中包含
<div>
<p>
some text, and maybe nodes <note>A note</note><lb />
and some more text<lb />
final line without lb
</p>
</div>我想把它转换成:
<div>
<lg>
<l>some text, and maybe nodes <note>A note</note></l>
<l>and some more text</l>
<l>final line without lb</l>
</lg>
</div>将p转换为lg是非常简单的。
<xsl:template match="tei:div/tei:p">
<lg>
<xsl:apply-templates/>
</lg>
</xsl:template>但剩下的我不知道该怎么做。将一系列节点转换为新父级的子节点。
如果有XSLT1.0的解决方案,它会很棒吗?
发布于 2017-03-17 16:56:14
您可以在这里使用名为门窗群的技术。在这种情况下,您可以将p元素的子节点按它们后面的lb元素的数量分组。
<xsl:key name="p-nodes" match="tei:p/node()" use="concat(generate-id(..), '|', count(following-sibling::tei:lb))" />要获得每个组中的第一个节点,它将表示您希望输出的每个l,您可以像这样选择它们.
<xsl:for-each
select="node()[generate-id() = generate-id(key('p-nodes', concat($parentId, '|', count(following-sibling::tei:lb)))[1])]">若要输出<l>标记本身和组的内容,请再次使用键.
<l><xsl:apply-templates select="key('p-nodes', concat($parentId, '|', count(following-sibling::tei:lb)))[not(self::tei:lb)]" /></l>尝试这个XSLT (显然,更改tei前缀的命名空间以匹配XML中的真正名称空间)
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:tei="tei">
<xsl:output method="xml" indent="yes" />
<xsl:key name="p-nodes" match="tei:p/node()" use="concat(generate-id(..), '|', count(following-sibling::tei:lb))" />
<xsl:template match="tei:div/tei:p">
<lg>
<xsl:variable name="parentId" select="generate-id()" />
<xsl:for-each select="node()[generate-id() = generate-id(key('p-nodes', concat($parentId, '|', count(following-sibling::tei:lb)))[1])]">
<l><xsl:apply-templates select="key('p-nodes', concat($parentId, '|', count(following-sibling::tei:lb)))[not(self::tei:lb)]" /></l>
</xsl:for-each>
</lg>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>在http://xsltransform.net/gWEamMf上看到它的动作
发布于 2017-03-17 17:10:22
这是另一种你可以看的方法。它使用键将每个节点链接到最近的lb分隔符。这使您能够通过前导分隔符的唯一id获取每个组(第一个组除外):
XSLT1.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:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:key name="following-nodes" match="node()[not(self::lb)]" use="generate-id(preceding-sibling::lb[1])" />
<xsl:template match="p[lb]">
<lg>
<l>
<xsl:apply-templates select="lb[1]/preceding-sibling::node()"/>
</l>
<xsl:for-each select="lb">
<l>
<xsl:apply-templates select="key('following-nodes', generate-id())"/>
</l>
</xsl:for-each>
</lg>
</xsl:template>
</xsl:stylesheet>此示例不使用名称空间,因为您的问题没有定义它们。
https://stackoverflow.com/questions/42862888
复制相似问题