簡體   English   中英

如何在XSLT 1.0中將數字/字母文本字符串分成兩個XML元素?

[英]How can I separate a number/alpha text string into two XML elements in XSLT 1.0?

在XSLT 1.0中是否可以將數字/字母文本字符串分成兩個XML元素?

我的輸入XML是:

<root>
<tocsectionnumber>1Funding and investing</tocsectionnumber>
<tocsectionnumber>2Rules and articles</tocsectionnumber>
<tocsectionnumber>3Summary and conclusion</tocsectionnumber>
</root>

我希望我的輸出是:

<TocItem>
<TocItemNumber>1</TocItemNumber>
<TocItemTitle>Funding and investing</TocItemTitle>
</TocItem>
<TocItem>
<TocItemNumber>2</TocItemNumber>
<TocItemTitle>Rules and articles</TocItemTitle>
</TocItem>
<TocItem>
<TocItemNumber>3</TocItemNumber>
<TocItemTitle>Summary and conclusion</TocItemTitle>
</TocItem>

我的數字字符串可以是任何1-3位數字,而字母字符串則是標題/標題。

任何指導是非常感謝。

謝謝。

您必須使用遞歸模板來計算前導數字,例如

<xsl:template name="leadingDigits">
  <xsl:param name="text" select="." />
  <xsl:param name="count" select="0" />
  <xsl:choose>
    <!-- check if the first character is a digit - when converted to number, any
         digit will equal itself, any non-digit will be NaN which does _not_
         equal itself -->
    <xsl:when test="number(substring($text, 1, 1)) =
                    number(substring($text, 1, 1))">
      <xsl:call-template name="leadingDigits">
        <xsl:with-param name="text" select="substring($text, 2)" />
        <xsl:with-param name="count" select="$count + 1" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$count" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

現在,您可以使用它來將字符串分成兩部分

<xsl:template match="tocsectionnumber">
  <xsl:variable name="numDigits">
    <xsl:call-template name="leadingDigits" />
  </xsl:variable>

  <TocItem>
    <TocItemNumber>
      <xsl:value-of select="substring(., 1, $numDigits)" />
    </TocItemNumber>
    <TocItemTitle>
      <xsl:value-of select="substring(., $numDigits + 1)" />
    </TocItemTitle>
  </TocItem>
</xsl:template>

[gro吟]誰來解決這些問題?

無論如何,可以這樣嘗試:

XSLT 1.0

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

<xsl:template match="/">
    <root>
        <xsl:for-each select="root/tocsectionnumber">
            <xsl:variable name="firstChar" select="substring(translate(., '0123456789', ''), 1, 1)" />
            <TocItem>
                <TocItemNumber><xsl:value-of select="substring-before(., $firstChar)"/></TocItemNumber>
                <TocItemTitle><xsl:value-of select="concat($firstChar, substring-after(., $firstChar))"/></TocItemTitle>
            </TocItem>
        </xsl:for-each>
    </root>
</xsl:template>

</xsl:stylesheet>

請注意,如果部分標題合法地以數字開頭,例如“ 4. 101種娛樂朋友和家人的方式”,則此(或任何其他方法)將遭到皇家轟炸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM