0

如何显示标题属性?

我想从@name中提取数据。

<specs>
<spec name="b_homologation">1</spec>
<spec name="s_homologation_type">mo</spec>
<spec name="b_xl">0</spec>
<spec name="b_runflat">0</spec>
<spec name="s_consumption">e</spec>
<spec name="i_noise">72</spec>
<spec name="s_grip">c</spec>
</specs>

结果必须是:

<field name="b_homologation">1</field>
<field name="s_homologation_type">mo</field>
...

谢谢。

编辑:

  <xsl:template match="*|@*">
    <xsl:call-template name="field">
      <xsl:with-param name="value" select="."/>
    </xsl:call-template>
  </xsl:template>
  <xsl:template name="field">
    <xsl:param name="name" select="name()" />
    <xsl:param name="value" select="text()" />
      <field name="{$name}">
        <xsl:value-of select="$value" />
      </field>
  </xsl:template>

结果是(不正确):

<field name="specs">1mo00e72c</field>
4

2 回答 2

2

正如我在评论中建议的那样,这里没有必要乱用命名模板和参数,它只是一个带有调整的简单身份转换:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <!-- copy input to output verbatim ... -->
  <xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
  </xsl:template>

  <!-- ... except spec elements, whose name changes to field -->
  <xsl:template match="spec">
    <field><xsl:apply-templates select="@*|node()" /></field>
  </xsl:template>
</xsl:stylesheet>

这将产生

<specs>
<field name="b_homologation">1</field>
<field name="s_homologation_type">mo</field>
<field name="b_xl">0</field>
<field name="b_runflat">0</field>
<field name="s_consumption">e</field>
<field name="i_noise">72</field>
<field name="s_grip">c</field>
</specs>

如果您想将根specs元素重命名为类似的名称,您可以使用相同的技巧fields,但如果您希望输出格式正确的 XML,则不能完全忽略它。

于 2013-06-26T14:46:01.443 回答
-1

像这样的东西?没有测试它,可以包含一些小错误:)

<xsl:template match="spec" >
    <xsl:call-template name="outputToXml" >
        <xsl:with-param name="name" select="@name" />
        <xsl:with-param name="value" select="." />
    </xsl:call-template>
</xsl:template>

<xsl:template name="outputToXml" >
    <xsl:param name="name" />
    <xsl:param name="value" />

    <xsl:text>&lt;field name="</xsl:text>
        <xsl:value-of select="$name" />
        <xsl:text>"&gt;</xsl:text>
        <xsl:value-of select="$value" />
        <xsl:text>&lt;/field&gt;</xsl:text>
</xsl:template>
于 2013-06-26T14:41:43.990 回答