2017-08-13 40 views
0

我遇到了一个XSLT转换问题,我正在尝试执行此操作。在整个项目中,我正在努力将XML文档转换为CSV文件以供数据库上传。问题是XML将日期作为ISO8601格式(YYYY-MM-DDT00:00:00)中的属性值发送,但是为了让数据库从CSV文件中获取数据,我需要将其转换为MM/DD/YYYY。使用XSLT格式XML属性值的日期

下面是一个XML示例:

<GetChanged> 
    <UserInformation> 
    <Column Name="id" Value="555555555"/> 
    <Column Name="name" Value="Kevin"/> 
    <Column Name="bday" Value="1990-01-01T00:00:00"/> 
    </UserInformation> 
</GetChanged> 

这里是我试图使用XSLT:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:csv="csv:csv"> 

<xsl:output method="text"/> 

<xsl:template match="GetChanged"> 
<!-- header --> 
    <xsl:text>"id","name","bday"&#10;</xsl:text> 
<!-- data rows --> 
<xsl:for-each select="UserInformation"> 

    <!-- data cells --> 
    <xsl:for-each select="Column[@Name='id']"> 
    <xsl:text>"</xsl:text> 
    <xsl:value-of select="@Value"/> 
    <xsl:text>"</xsl:text> 
</xsl:for-each> 
<xsl:text>,</xsl:text> 
    <xsl:for-each select="Column[@Name='name']"> 
    <xsl:text>"</xsl:text> 
    <xsl:value-of select="@Value"/> 
    <xsl:text>"</xsl:text> 
</xsl:for-each> 
<xsl:text>,</xsl:text> 
    <xsl:for-each select="Column[@Name='bday']"> 
    <xsl:text>"</xsl:text> 
    <xsl:value-of select="format-date(@Value, '[M01]/[D01]/[Y0001]')"/> 
    <xsl:text>"</xsl:text> 
</xsl:for-each> 
      <xsl:if test="position()!=last()"> 
      <xsl:text>,</xsl:text> 
      </xsl:if> 
     <xsl:text>&#10;</xsl:text> 
    </xsl:for-each> 
</xsl:template> 

</xsl:stylesheet> 

然而,当我使用引入nokogiri运行此通过红宝石,我最终得到一个错误:

RuntimeError:运行时错误:元素值 - XPath评估返回无结果

关于我能做些什么来适当地设置这个日期的想法?

在此先感谢!

+0

你确定你的处理器支持XSLT 2.0吗? –

回答

0

表示为YYYY-MM-DDT00:00:00的值不是日期。尝试改变:

<xsl:value-of select="format-date(@Value, '[M01]/[D01]/[Y0001]')"/> 

到:

<xsl:value-of select="format-dateTime(@Value, '[M01]/[D01]/[Y0001]')"/> 

注意,这两种功能需要一个XSLT 2.0处理器。如果您的处理器只支持XSLT 1.0,您可以使用字符串操作格式化日期:

<xsl:value-of select="substring(@Value, 6, 2)"/> 
<xsl:text>/</xsl:text> 
<xsl:value-of select="substring(@Value, 9, 2)"/> 
<xsl:text>/</xsl:text> 
<xsl:value-of select="substring(@Value, 1, 4)"/> 
+0

Nokogiri不支持XSLT 2.0 –

0

引入nokogiri取决于libxslt的XSLT。

In Nokogiri 1.6.0 and later libxml2 and libxslt are bundled with the gem, but if you want to use the system versions:

(在这里看到更多的细节:https://github.com/sparklemotion/nokogiri

libxslt只支持XSLT的1.0

A separate library called libxslt is available implementing XSLT-1.0 for libxml2

(详情请看这里:http://xmlsoft.org/XSLT.html

你可以解决由使用像这样的解决方案:Convert date from DD-MMM-YYYY to YYYYMMDD format in xslt 1.0

或做一些像这里描述的子字符串/ concat:Displaying Date as DD-MM-YYYY within XSLT/XML