我正在使用XSLT将xml模式转换为JSON格式,其中有一个模式方面,如下所示:
<simpleType>
<restriction base="string">
<pattern value="[A-Z0-9a-z_]+(@{UUID}|@{TIMEMILLIS})?[A-Z0-9a-z]*"/>
</restriction>
</simpleType>
虽然正则表达式转义需要"\"字符,但在转换为 JSON 时需要进一步转义。
我正在使用带有撒克逊语的 XSLT 3.0,如下所示:
<if test="child::xsi:simpleType/child::xsi:restriction/child::xsi:pattern">
<text>,"pattern":"</text><value-of select="replace(attribute::value,'\','\')"/><text>"</text>
</if>
输出仍然是
"pattern": "[A-Z0-9a-z_]+(@{UUID}|@{TIMEMILLIS})?[A-Z0-9a-z]*"
在 JSON 中。我已经尝试了许多组合,replace() 函数似乎在这里不起作用。
我可能错过了一些东西。我从这里引用函数定义。
任何帮助将不胜感激。
要将替换为
\
,您需要编写
replace($x, '\', '\\')
这是因为替换字符串中的转义规则。(规则选择不当,我们试图与其他语言兼容,但其他语言在这方面完全不一致。
还有另一种选择:使用"q"标志:
replace($x, '', '\', 'q')
使用 XSLT 和 XPath 3 中的支持进行 JSON 创建和序列化,例如创建映射和序列化为 JSON
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all"
version="3.0">
<xsl:mode on-no-match="shallow-skip"/>
<xsl:output method="json" indent="yes"/>
<xsl:template match="pattern">
<xsl:sequence select="map { local-name() : data(@value) }"/>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/pPzifoX
或创建 xml-to-json
函数所需的 XML 格式:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.w3.org/2005/xpath-functions"
exclude-result-prefixes="#all"
expand-text="yes"
version="3.0">
<xsl:mode on-no-match="shallow-skip"/>
<xsl:strip-space elements="*"/>
<xsl:output method="text" indent="yes"/>
<xsl:variable name="json-xml">
<xsl:apply-templates/>
</xsl:variable>
<xsl:template match="/">
<xsl:value-of select="xml-to-json($json-xml, map { 'indent' : true() })"/>
</xsl:template>
<xsl:template match="pattern">
<map>
<string key="{local-name()}">{@value}</string>
</map>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/pPzifoX/1