XSLT - 通过检查现有属性向现有节点添加新属性

XSLT - Add new attribute to existing node by checking existing attribute

你好,我有关注xml,

<doc>
 <footnote>
   <p type="Footnote Text">
       <link ref="http://www.facebook.org"/>
   </p>
 </footnote>
<footnote>
   <p type="Footnote Text">
       <link ref="http://www.wiki.org"/>
   </p>
 </footnote>
<footnote>
   <p type="Footnote Paragraph">
       <link ref="http://www.wiki.org"/>
   </p>
 </footnote>
</doc>

我需要做的是将新属性 (id='number-1') 添加到 <p> 节点,其属性 type 等于 Footnote Text。在这种情况下,只有前两个 <p> 节点应应用新的 <id> 属性。

所以我写了下面的代码,

<xsl:template match="p/@type[.='Footnote Text']">
   <xsl:copy>
      <xsl:attribute name="id">
         <xsl:value-of select="'number-'"/><xsl:number level="any"/>
      </xsl:attribute>
      <xsl:apply-templates select="node()|@*"/>
   </xsl:copy>
</xsl:template>

但它不会将新属性添加到 <p> 节点。但是,当我删除 @type[.='Footnote Text'] 时,它会按预期将新节点添加到所有 <p> 节点。

我的预期输出如下

<doc>
   <footnote>
      <p type="Footnote Text" id="number-1">
          <link ref="http://www.facebook.org"/>
      </p>
   </footnote>
   <footnote>
     <p type="Footnote Text" id="number-2>
        <link ref="http://www.wiki.org"/>
     </p>
   </footnote>
   <footnote>
     <p type="Footnote Paragraph">
       <link ref="http://www.wiki.org"/>
     </p>
   </footnote>
 </doc>

如何过滤具有 type="Footnote Text" 属性的 <p> 节点并向这些 <p> 节点添加新属性?

您需要将属性添加到元素:

<xsl:template match="p[@type = 'Footnote Text']">
   <xsl:copy>
      <xsl:attribute name="id">
         <xsl:value-of select="'number-'"/><xsl:number count="p[@type = 'Footnote Text']" level="any"/>
      </xsl:attribute>
      <xsl:apply-templates select="node()|@*"/>
   </xsl:copy>
</xsl:template>