xslt transform (json to csv)



我正在尝试使用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?

提前感谢

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

<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的方言开始做自己的事情…(

最新更新