【发布时间】:2014-05-12 13:45:31
【问题描述】:
我正在尝试将下面的逗号分隔标签列表拆分为单独的元素。 XML 源中的元素和属性名称将始终相同。我使用的是 1.0,所以我希望有一个 1.0 的解决方案。基于this similar example,我认为以下 XSL 可以工作:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output indent="yes"/>
<xsl:template match="pbcoreCollection">
<pbcoreCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<pbcoreDescriptionDocument>
<xsl:call-template name="tokenize">
<xsl:with-param name="text" select="instantiationannotation"/>
<xsl:with-param name="elemName" select="'instantitionAnnotation'"/>
</xsl:call-template>
</pbcoreDescriptionDocument>
</pbcoreCollection>
</xsl:template>
<xsl:template name="tokenize">
<xsl:param name="text"/>
<xsl:param name="elemName"/>
<xsl:param name="sep" select="', '"/>
<xsl:choose>
<xsl:when test="contains($text, $sep)">
<xsl:element name="{$elemName}">
<xsl:value-of select="substring-before($text, $sep)"/>
</xsl:element>
<!-- recursive call -->
<xsl:call-template name="tokenize">
<xsl:with-param name="text" select="substring-after($text, $sep)" />
<xsl:with-param name="elemName" select="$elemName" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:element name="{$elemName}">
<xsl:value-of select="$text"/>
</xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
但它会产生结果
<?xml version="1.0"?>
<pbcoreCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<pbcoreDescriptionDocument>
<instantitionAnnotation/>
</pbcoreDescriptionDocument>
</pbcoreCollection>
我的原始 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pbcoreCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<pbcoreDescriptionDocument>
<pbcoreInstantiation>
<instantiationAnnotation annotationType="CMS tag">congress, guns, gun_policy, catholic_schools, social_media, </instantiationAnnotation>
</pbcoreInstantiation>
</pbcoreDescriptionDocument>
</pbcoreCollection>
我希望看起来像这样:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pbcoreCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<pbcoreDescriptionDocument>
<pbcoreInstantiation>
<instantiationAnnotation annotationType="CMS tag">congress</instantiationAnnotation>
<instantiationAnnotation annotationType="CMS tag">gun</instantiationAnnotation>
<instantiationAnnotation annotationType="CMS tag">gun_policy</instantiationAnnotation>
<instantiationAnnotation annotationType="CMS tag">catholic_schools</instantiationAnnotation>
<instantiationAnnotation annotationType="CMS tag">social_media</instantiationAnnotation>
</pbcoreInstantiation>
</pbcoreDescriptionDocument>
</pbcoreCollection>
【问题讨论】:
-
类似的问题得到了很好的回答here。
-
您可以使用哪个版本的 XSLT? 1.0、2.0、3.0?使用 XSLT 1.0 有点复杂,但并非不可能,但在 2.0 或 3.0 中却很简单。
-
1. “我见过一些类似的问题/答案,但与我正在尝试做的完全不一样。” 也许不是确切地说,但是awfully close 2. 一个例子不能很好地定义一个问题:XML 源中的元素和属性名称是否总是相同的?如果是,答案可以简化。
-
我来看看那个例子,我以前没见过,谢谢。在这种情况下,是的,XML 源中的元素和属性名称将始终相同。