我正在将 XSLT 从源 XML 转换为 JSON。我希望将数组类型元素转换为“elements : []”
从给定的 xslt 中,我匹配节点名称并应用模板。但是如何为每个数组类型元素动态执行此操作,或者我可以选择需要将哪个元素转换为 JSON 中的数组类型元素。
这是我的源 XML
<order>
<email><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee3effce5a0e6cef7e1fee3efe7e2a0ede1e3" rel="noreferrer noopener nofollow">[email protected]</a></email>
<tax-lines>
<tax-line>
<title>CGST</title>
<price>29.00</price>
<rate>0.2</rate>
</tax-line>
</tax-lines>
<freight-Lines>
<freight-Line>
<title>CGST</title>
<price>29.00</price>
<rate>0.2</rate>
</freight-Line>
</freight-Lines>
</order>
XSLT:
<xsl:when test="name()= 'tax-lines'">
[<xsl:apply-templates select="*" mode="ArrayElement"/>]
</xsl:when>
使用它,我的输出 Json 为:
{
"order" :
{
"email" :"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="016c60736a2f6941786e716c60686d2f626e6c" rel="noreferrer noopener nofollow">[email protected]</a>",
"tax-lines" :
[
{
"title" :"CGST",
"price" :"29.00",
"rate" :"0.2"
}
]
}
}
无论如何,我可以动态地对“freight-Lines”数组执行相同的操作吗?意味着我想动态地执行此操作
<xsl:when test="name()= 'tax-lines'">
[<xsl:apply-templates select="*" mode="ArrayElement"/>]
</xsl:when>
最佳答案
解决这个问题的一种方法是使用某种映射模式来控制转换。所以你可能有:
由此,您可以生成包含一组模板规则的样式表,例如:
<xsl:template match="tax-lines | freight-lines">
<xsl:text>[</xsl:text>
<xsl:for-each select="*">
<xsl:if test="position() != 1">,</xsl:if>
<xsl:apply-templates select="."/>
<xsl:text>]</xsl:text>
</xsl:template>
<xsl:template match="tax-line | freight-line">
<xsl:text>{</xsl:text>
<xsl:for-each select="*">
<xsl:if test="position() != 1">,</xsl:if>
<xsl:text>"</xsl:text>
<xsl:value-of select="local-name()"/>
<xsl:text>":</xsl:text>
<xsl:apply-templates select="."/>
<xsl:text>}</xsl:text>
</xsl:template>
<xsl:template match="*[. castable as xs:double]">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="*">
<xsl:text>"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
</xsl:template>
因此,您基本上拥有一组用于将不同 XML 元素映射到 JSON 的模式,每个模式都有一个框架模板规则;您的映射架构定义源文档中每个元素使用的模式(使用默认值),然后将映射架构转换为将每个元素名称与相应模板规则相关联的样式表。
关于xml - 如何使用 name() 动态应用模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50037776/