【问题标题】:Get the date of each month using xslt使用 xslt 获取每个月的日期
【发布时间】:2017-04-25 06:44:57
【问题描述】:

我需要使用 xslt v2 根据输入文件获取每个月的日期。这是我的示例数据:

<Data>
   <Field>March/02/2017/February/16/1989/December/19/2015</Field>
</Data>

我的 XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="Data">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>
<xsl:variable name="months" select="'January','February','March','April','May','June','July','August','September','October','November','December'"/>
<xsl:template match="Field">
    <xsl:variable name="Output">
        <xsl:analyze-string select="normalize-space(.)" regex="([A-Z][a-z]+)">
            <xsl:matching-substring>
                <xsl:number value="index-of($months, regex-group(1))" format="01"/>
            </xsl:matching-substring>
        </xsl:analyze-string>
    </xsl:variable>
    <Result>
        <xsl:value-of select="$Output"/>
    </Result>
</xsl:template>
</xsl:stylesheet>

生成的输出

<Data>
   <Result>030212</Result>
</Data>

生成的输出是每个月的位置,但我想在每个月之后填充日期。喜欢这个:

<Data>
   <March>02/2017</March>
   <February>16/1989</February>
   <December>19/2015</December>
</Data>

另外,如果测试文件中的月份是大写或小写,我会遇到问题,它没有填充输出。我

希望你能帮助我。谢谢。

【问题讨论】:

  • 您想要生成的输出将难以处理。您确定要制作这种格式吗?
  • 是的,这是我需要生成的。但输出元素名称只是一个示例。

标签: xml xslt xslt-2.0


【解决方案1】:

我不确定我是否理解$monthsindex-of() 的原因。看起来一切都已经在 Field 中了。

示例...

XSLT 2.0

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

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

  <xsl:template match="Field">
    <xsl:analyze-string select="normalize-space()" regex="(\w+)/(\d{{2}}/\d{{4}})">
      <xsl:matching-substring>
        <xsl:element name="{regex-group(1)}">
          <xsl:value-of select="regex-group(2)"/>
        </xsl:element>
      </xsl:matching-substring>
    </xsl:analyze-string>
  </xsl:template>

</xsl:stylesheet>

输出

<Data>
   <March>02/2017</March>
   <February>16/1989</February>
   <December>19/2015</December>
</Data>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    相关资源
    最近更新 更多