【问题标题】:XSLT - add attribute and new node to existing nodeXSLT - 将属性和新节点添加到现有节点
【发布时间】:2015-07-13 07:17:23
【问题描述】:

我需要向现有节点添加属性和新节点

例子:

<doc>
  <a></a>
  <a></a>
  <a></a>
  <d></d>
  <a></a>
  <f></f>
</doc>

我现在需要添加 &lt;a&gt; 节点的属性并在节点内添加新节点。

所以输出会是,

<doc>
  <a id='myId'> <new_node attr="myattr"/> </a>
  <a id='myId'> <new_node attr="myattr"/> </a>
  <a id='myId'> <new_node attr="myattr"/> </a>
  <d></d>
  <a id='myId'> <new_node attr="myattr"/> </a>
  <f></f>
</doc>

我编写了以下代码来完成这项任务,

<xsl:template match="a">

        <xsl:apply-templates select="@*|node()"/>
        <xsl:copy> 
            <xsl:attribute name="id">
                <xsl:value-of select="'myId'"/>
            </xsl:attribute>      
        </xsl:copy>    

         <new_node>
               <xsl:attribute name="attr">
                   <xsl:value-of select="'myattr'"/>
               </xsl:attribute>
         </new_node>
</xsl:template>

此代码按预期添加了新属性和新节点,但问题是它只添加到第一个节点,并且在氧气编辑器中它和以下五个消息之后不编译。 ' An attribute node (id) cannot be created after a child of the containing element.

我该如何解决这个问题?

【问题讨论】:

    标签: xml xslt xslt-2.0


    【解决方案1】:

    您在正确的路线上,但您需要确保在任何属性之后添加任何子节点。必须先添加属性,然后再添加任何子节点。

    试试这个模板

    <xsl:template match="a">
        <xsl:copy> 
            <xsl:apply-templates select="@*"/>
            <xsl:attribute name="id">
                <xsl:value-of select="'myId'"/>
            </xsl:attribute>      
            <xsl:apply-templates select="node()"/>
            <new_node>
               <xsl:attribute name="attr">
                   <xsl:value-of select="'myattr'"/>
               </xsl:attribute>
            </new_node>
        </xsl:copy>    
    </xsl:template>
    

    其实你可以稍微简化一下,直接写出属性。也试试这个

    <xsl:template match="a">
        <a id="myId"> 
            <xsl:apply-templates select="@*|node()"/>
           <new_node attr="myattr" />
        </a>    
    </xsl:template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 2012-08-03
      • 2018-05-31
      相关资源
      最近更新 更多