我正在尝试在 xpath 中将字母 (ABC) 更改为数字 (123)

I am trying to change letters (ABC) into numbers (123) in xpath

我是 Xpath 的新手,正在努力使用某些功能。这是 XML 文件的基本版本。我想把id改成一个属性,然后把字母B改成数字。我将输出写为 XML.

<artists>
  <artist>
    <id>B</id>
    <name>John Sunday</name>
  </artist>
</artist>

这是我在 XSL 中所做的:

<xsl:template match="artist">
   <artist>
     <xsl:attribute name="id">
         <xsl:apply-templates select="id"/>
     </xsl:attribute>
     <name><xsl:value-of select="name"/></name>
   </artist>

<xsl:template match="id">
    <xsl:value-of select="translate('BCD','BCD','123')"/>
</xsl:template>

然后得到如下输出:

<artist id="123">
<name>John Sunday</name>
</artist>

我只希望它位于的位置:

<artist id="1">
<name>John Sunday</name>
</artist>

下一位艺术家是“2”

只需更改此

<xsl:template match="id">
  <xsl:value-of select="translate('BCD','BCD','123')"/>
</xsl:template>

<xsl:template match="id">
  <xsl:value-of select="translate(.,'BCD','123')"/>
</xsl:template>

由于您的模板与 id 相匹配,.id 的当前值。

如果这应用于示例输入 XML

<artists>
  <artist>
    <id>B</id>
    <name>John Sunday</name>
  </artist>
  <artist>
    <id>C</id>
    <name>John Monday</name>
  </artist>
  <artist>
    <id>D</id>
    <name>John Tuesday</name>
  </artist>
</artists>

生成以下输出:

<artist id="1">
  <name>John Sunday</name>
</artist> 
<artist id="2">
  <name>John Monday</name>
</artist> 
<artist id="3">
  <name>John Tuesday</name>
</artist>

供参考:https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/translate
作为进一步的解释:对于语法 translate(string, toReplace, replacement),模板匹配 id 中的 <xsl:value-of select="translate('BCD','BCD','123')"/>BCD 转换为 123 的值分配为第一个参数- string - 不是当前的 id 值,而是字符串 BCD.

或者只是:

<xsl:template match="artist">
    <artist id="{translate(id,'BCD','123')}">
        <xsl:copy-of select="name"/>
    </artist>
</xsl:template>