xml - 如何使用 name() 动态应用模板?

标签 xml xslt

我正在将 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/

相关文章:

java - 为什么这个值在xsd的生成中是 '29801000199002684333'长,为什么不是varchar

xml - XSLT:获取存在某一特定值的节点

xslt - 从 Java Servlet 读取文件

html - 如何消除使用 XSLT 转换的 HTML 中不正确的 xmlns 属性

java - 将 Java GUI 序列化为 XML

java - 安卓按键延迟?

java - 使用 JAXB 读取 XML 文件

xslt - 如何获取模板内的模板名称

xslt - 理解 `apply-templates`匹配

xml - 在 JAXB 中编码数组