[英]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><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>
所需的 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(., '<n>')]">
<xsl:variable name="n">
<xsl:number count="text[starts-with(., '<n>')]" level="any"/>
</xsl:variable>
<xsl:copy>
<xsl:value-of select="$n + 1" />
<xsl:value-of select="substring-after(., '<n>')" />
</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.