Xslt 转换异常。在子元素后添加属性

Xslt 转换异常。在子元素后添加属性,xslt,Xslt,我有以下XML: <root> <tab name="Detail"> <section name="mysection"> <items level="1"> <Idx_name>9</Idx_name> <Type>mytype</Type> <item na

我有以下XML:

    <root>   
      <tab name="Detail">
        <section name="mysection">
          <items level="1">
            <Idx_name>9</Idx_name>
            <Type>mytype</Type>
            <item name="myname">
              <Grams um="(g)">9,0</Grams>
              <Pre-infusion>Max</Pre-infusion>
            </item>
            <Std._Mode>On</Std._Mode>
            <Price>100</Price>
          </items>
        </section>   
    </tab> 
</root>

9
mytype
9,0
马克斯
在…上
100
这个XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="node()">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates select="node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="items/*">
    <xsl:choose>
      <xsl:when test="not(name()='item')">
        <xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute>
      </xsl:when>
      <xsl:otherwise>
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:value-of select="."/>
        </xsl:copy>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

现在,我想要的是:

<root>
  <tab name="Detail">
    <section name="mysection">
      <items level="1" Idx_name="9" Type="mytype" Std._Mode="On" Price="100">
        <item name="myname">9,0Max</item>
      </items>
    </section>
  </tab>
</root>

9,0Max
我得到错误:“不能在子级之后添加属性”

不幸的是,我无法更改原始XML的节点项中元素的顺序

我怎么做

谢谢


Ivan

确保您首先处理要转换为属性的元素,例如使用XSLT 2.0,您可以处理顺序为的序列

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="items">
  <xsl:copy>
    <xsl:apply-templates select="@*, * except item, item"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="items/*[not(self::item)]">
  <xsl:attribute name="{name()}" select="."/>
</xsl:template>

<xsl:template match="items/item">
  <xsl:copy>
    <xsl:apply-templates select="@*"/>
    <xsl:value-of select="."/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>


使用XSLT1.0,您需要按照您想要的顺序拼写出几个
应用模板。

谢谢Martin,您出色地解决了我的问题。非常感谢。