XSL将子元素复制到父属性

时间:2015-05-14 13:34:23

标签: xslt attributes parent-child elements

我刚刚开始学习XLS,只需在下面修改我的XML。特别是,我想复制<description>元素的值,并将其替换为其父name的{​​{1}}属性。

源XML:

<game>

期望的输出:

<?xml version="1.0"?>
<menu>
   <game name="$100000P" index="" image="">
      <description>$100,000 Pyramid (1988)</description>
      <cloneof></cloneof>
      <crc></crc>
      <manufacturer>Box Office, Inc.</manufacturer>
      <year>1988</year>
      <genre>Strategy</genre>
      <rating></rating>
      <enabled>Yes</enabled>
   </game>
   <game name="$takes" index="" image="">
      <description>High Stakes by Dick Francis (1986)</description>
      <cloneof></cloneof>
      <crc></crc>
      <manufacturer>Mindscape, Inc.</manufacturer>
      <year>1986</year>
      <genre>Adventure</genre>
      <rating></rating>
      <enabled>Yes</enabled>
   </game>
   <game name="007Licen" index="" image="">
      <description>007 -  Licence to Kill (1989)</description>
      <cloneof></cloneof>
      <crc></crc>
      <manufacturer>Domark Ltd.</manufacturer>
      <year>1989</year>
      <genre>Driving</genre>
      <rating></rating>
      <enabled>Yes</enabled>
   </game>
...

我曾尝试过以下XSL,但它似乎没有做任何更改。现在真的摸不着头脑。

<?xml version="1.0"?>
<menu>
   <game name="$100,000 Pyramid (1988)" index="" image="">
      <description>$100,000 Pyramid (1988)</description>
      <cloneof></cloneof>
      <crc></crc>
      <manufacturer>Box Office, Inc.</manufacturer>
      <year>1988</year>
      <genre>Strategy</genre>
      <rating></rating>
      <enabled>Yes</enabled>
   </game>
   <game name="High Stakes by Dick Francis (1986)" index="" image="">
      <description>High Stakes by Dick Francis (1986)</description>
      <cloneof></cloneof>
      <crc></crc>
      <manufacturer>Mindscape, Inc.</manufacturer>
      <year>1986</year>
      <genre>Adventure</genre>
      <rating></rating>
      <enabled>Yes</enabled>
   </game>
   <game name="007 - Licence to Kill (1989)" index="" image="">
      <description>007 -  Licence to Kill (1989)</description>
      <cloneof></cloneof>
      <crc></crc>
      <manufacturer>Domark Ltd.</manufacturer>
      <year>1989</year>
      <genre>Driving</genre>
      <rating></rating>
      <enabled>Yes</enabled>
   </game>

1 个答案:

答案 0 :(得分:2)

您的方法存在问题:当您这样做时:

<xsl:apply-templates select="@*|node()"/>

您还会复制原始@name属性,覆盖刚刚创建的新@name属性。

尝试改为:

<xsl:template match="game">
    <game>
        <xsl:copy-of select="@*"/>
        <xsl:attribute name="name">
            <xsl:value-of select="description"/>
        </xsl:attribute>
        <xsl:apply-templates select="node()"/>
    </game>
</xsl:template>

或者,如果您知道game将拥有的所有属性:

<xsl:template match="game">
    <game name="{description}" index="{@index}" image="{@image}">
        <xsl:apply-templates select="node()"/>
    </game>
</xsl:template>