繁体   English   中英

使用 XSLT 2.0 在输入 XML 中用序列号替换占位符

[英]Replacing placeholders with sequence numbers in input XML using XSLT 2.0

我输入了 XML,如下所示:

<parent>
  <data>
    <text>1.This is sample text1.</text>
  </data>
  <data>
    <text>This is sample text without number.</text>
  </data>
  <data>
    <text>&lt;n&gt;.This is sample text2.</text>
  </data>
  <data>
    <text>&lt;n&gt;.This is sample text3.</text>
  </data>
  <data>
    <text>&lt;n&gt;.This is sample text4.</text>
  </data>
</parent>

所需的 output xml 如下:

<parent>
  <data>
    <text>1.This is sample text1.</text>
  </data>
  <data>
    <text>This is sample text without number.</text>
  </data>
  <data>
    <text>2.This is sample text2.</text>
  </data>
  <data>
    <text>3.This is sample text3.</text>
  </data>
  <data>
    <text>4.This is sample text4.</text>
  </data>
</parent>

我需要用 XSLT 2.0 中的解决方案将 <n> 替换为从 2 开始的序列号。 我尝试使用 for-each 替换 function 和模板以及替换 function。 但是在模板中我不会得到 position() 值。 您能否指导我如何实现这一目标?

我需要用从 2 开始的序列号替换 <n>

怎么样:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="text[starts-with(., '&lt;n&gt;')]">
    <xsl:variable name="n">
        <xsl:number count="text[starts-with(., '&lt;n&gt;')]" level="any"/>
    </xsl:variable>
    <xsl:copy>
        <xsl:value-of select="$n + 1" />    
        <xsl:value-of select="substring-after(., '&lt;n&gt;')" />   
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

没有严格回答这个问题,但我认为这属于这里。

除了处理字符串,您可能还想考虑处理 XML。

如果您将 XML 更改为:

<parent>
  <data>
    <text><n />. This is sample text1.</text>
  </data>
  <data>
    <text>This is sample text without number.</text>
  </data>
  <data>
    <text><n />. This is sample text2.</text>
  </data>
  <data>
    <text><n />. This is sample text3.</text>
  </data>
  <data>
    <text><n />. This is sample text4.</text>
  </data>
</parent>

(注意:我使用<n />而不是<n>以便 XML 有效)。

然后您可以使用以下 XSL 样式表,在我看来,它更符合“XML/XSL 哲学”。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="n">
    <xsl:value-of select="count(preceding::n) + 1" />
  </xsl:template>

</xsl:stylesheet>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM