【问题标题】:How do I inherit element names from the current XSLT context?如何从当前 XSLT 上下文继承元素名称?
【发布时间】:2016-07-01 06:59:39
【问题描述】:

我有一个这样的 XML 文档:

<?xml version="1.0" encoding="utf-8" ?>
<article properName="Article">
  <h1>
    This <strong>is a header</strong>
  </h1>
  <p>This is a <strong>paragraph</strong</p>
</article>

我需要把它转换成这个:

<?xml version="1.0" encoding="utf-8" ?>
<Article>
  <Article-bigheader>
    This <Article-bigheader-bold>is a header</Article-bigheader-bold>
  </Article-bigheader>
  <Article-paragraph>This is a <Article-paragraph-bold>paragraph</Article-paragraph-bold></Article-paragraph>
</Article>

原始文档中的元素将具有不同的名称并以不同的方式嵌套,因此我需要动态地执行此操作,而不是为每个可能的组合创建一个 xsl 模板。我遇到问题的具体部分是文本装饰,如何创建一个元素,其名称为包含 XSLT 元素的名称和附加的“-bold”后缀? 这是我到目前为止所得到的:

<xsl:template match="/article">
    <xsl:element name="{@properName}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>
<xsl:template match="h1">
    <xsl:element name="{concat(/article/@properName, '-', 'bigheader')}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

【问题讨论】:

  • 您使用的是 XSLT 1.0 还是 2.0?

标签: xml xslt


【解决方案1】:

也许你应该这样尝试:

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:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:param name="name"/>
    <xsl:copy>
        <xsl:apply-templates select="@*|node()">
            <xsl:with-param name="name" select="$name"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<xsl:template match="*[@properName]">
    <xsl:element name="{@properName}">
        <xsl:apply-templates>
            <xsl:with-param name="name" select="@properName"/>
        </xsl:apply-templates>
    </xsl:element>
</xsl:template>

<xsl:template match="h1">
    <xsl:param name="name"/>
    <xsl:element name="{concat($name, '-', 'bigheader')}">
        <xsl:apply-templates>
            <xsl:with-param name="name" select="concat($name, '-', 'bigheader')"/>
        </xsl:apply-templates>
    </xsl:element>
</xsl:template>

<xsl:template match="p">
    <xsl:param name="name"/>
    <xsl:element name="{concat($name, '-', 'paragraph')}">
        <xsl:apply-templates>
            <xsl:with-param name="name" select="concat($name, '-', 'paragraph')"/>
        </xsl:apply-templates>
    </xsl:element>
</xsl:template>

<xsl:template match="strong">
    <xsl:param name="name"/>
    <xsl:element name="{concat($name, '-', 'bold')}">
        <xsl:apply-templates>
            <xsl:with-param name="name" select="concat($name, '-', 'bold')"/>
        </xsl:apply-templates>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多