xslt转换(将json转换为csv)

时间:2020-10-11 18:44:22

标签: json xslt

我正在尝试使用xslt将json转换为csv。

这是我的XSLT样式表。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:array="http://www.w3.org/2005/xpath-functions/array"
    exclude-result-prefixes="#all"
    version="3.0">
    
  <xsl:param name="json-string" as="xs:string">[
    {
        "id": "1",
        "name": "manu"
    },
    {
        "id": "2",
        "name": "vivek"
    }
]</xsl:param>

  <xsl:param name="json-xml" select="json-to-xml($json-string)"/>

  <xsl:output method="text"/>

  <xsl:template match="/" name="xsl:initial-template">
    <xsl:value-of select="$json-xml/*/*!string-join(*, ',')" separator="&#10;"/>
  </xsl:template>
  
</xsl:stylesheet>

当数据本身带有逗号时,意味着应将特定数据括在双引号内。

示例:-

[
    {
        "id": "1",
        "name": "ma,nu"
    },
    {
        "id": "2",
        "name": "vivek"
    }
]

当前输出:-

1,ma,nu
2,vivek

例外的输出:-

1,"ma,nu"
2,vivek

如何修改上面的xslt?

预先感谢

1 个答案:

答案 0 :(得分:3)

string-join(*, ',')替换为string-join(*!f:escape(.), ',')并编写函数

<xsl:function name="f:escape" as="xs:string" expand-text="yes">
  <xsl:param name="in" as="xs:string"/>
  <xsl:choose>
    <xsl:when test="contains($in, ',')">"{$in}"</xsl:when>
    <xsl:otherwise>{$in}</xsl:otherwise>
  </xsl:choose>
</xsl:function>

(但是如果值还包含引号怎么办?此时,CSV的方言开始做自己的事...)

相关问题