获取XSLT中当前节点的子字符串

时间:2013-12-11 02:18:31

标签: xml xslt

我有这个XML输入:

<?xml version="1.0" encoding="utf-8"?>
<Document>
  <TopLevel>
    <Payments>
      <PaymentID>PID1</PaymentID>
      <Transaction>
        <TransID>TR1-PID1XX</TransID>
        <TransNumber>1</TransNumber>
      </Transaction>
      <Transaction>
        <TransID>TR1-PID1XY</TransID>
        <TransNumber>2</TransNumber>
      </Transaction>
      <Transaction>
        <TransID>TR1-PID1XX</TransID>
        <TransNumber>3</TransNumber>
      </Transaction>
    </Payments>
    <Payments>
      <PaymentID>PID2</PaymentID>
      <Transaction>
        <TransID>TR2-PID2XY</TransID>
        <TransNumber>4</TransNumber>
      </Transaction>
      <Transaction>
        <TransID>TR2-PID2XX</TransID>
        <TransNumber>5</TransNumber>
      </Transaction>
      <Transaction>
        <TransID>TR2-PID2XY</TransID>
        <TransNumber>6</TransNumber>
      </Transaction>
    </Payments>
  </TopLevel>
</Document>

这是我的XSLT:

<xsl:template match="Transaction">
    <Transaction>
      <xsl:apply-templates select="TransID"/>
    </Transaction>
  </xsl:template>

  <xsl:template match="TransID">
    <TransID>
      <xsl:value-of select="."/>
    </TransID>
    <TransNumber>
      <xsl:number level="any"/>
    </TransNumber>
    <xsl:if test="substring(//TransID,9,2)='XX'">
      <TransCode>
        <xsl:value-of select ="substring(//TransID,1,3)"/>
      </TransCode>
    </xsl:if>
  </xsl:template>

我的XSLT没有获取当前节点子字符串,而是总是得到第一个节点字符串,我错过了什么?

顺便说一句,这是我想要的输出:

<Payments>
  <PaymentID>PID1</PaymentID>
  <Transaction>
    <TransID>TR1-PID1XX</TransID>
    <TransNumber>1</TransNumber>
    <TransCode>TR11</TransCode>
  </Transaction>
  <Transaction>
    <TransID>TR1-PID1XY</TransID>
    <TransNumber>2</TransNumber>
  </Transaction>
  <Transaction>
    <TransID>TR1-PID1XX</TransID>
    <TransNumber>3</TransNumber>
    <TransCode>TR13</TransCode>
  </Transaction>
</Payments>
<Payments>
  <PaymentID>PID2</PaymentID>
  <Transaction>
    <TransID>TR2-PID2XY</TransID>
    <TransNumber>4</TransNumber>
  </Transaction>
  <Transaction>
    <TransID>TR2-PID2XX</TransID>
    <TransNumber>5</TransNumber>
    <TransCode>TR25</TransCode>
  </Transaction>
  <Transaction>
    <TransID>TR2-PID2XY</TransID>
    <TransNumber>6</TransNumber>
  </Transaction>
</Payments>

感谢所有这个美好的社区:)

1 个答案:

答案 0 :(得分:2)

因为您始终在整个文档中搜索所有TransID个节点。另外,由于节点集上的substring将对集合中的第一个节点进行操作,因此始终会查看第一个节点。

将其更改为以下内容,它应该可以正常工作。

<xsl:if test="substring(./text(),9,2)='XX'">
  <TransCode>
    <xsl:value-of select ="substring(./text(),1,3)"/>
  </TransCode>
</xsl:if>