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

时间:2015-03-07 11:53:20

标签: xml xslt 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”

2 个答案:

答案 0 :(得分:3)

或者只是:

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

答案 1 :(得分: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),模板匹配<xsl:value-of select="translate('BCD','BCD','123')"/>中的idBCD的转换分配为123作为值,作为第一个参数 - string - 不是当前的id值,而是字符串BCD

相关问题