递归XSLT转换以简化XML

时间:2013-10-31 12:56:42

标签: xml xslt

我有这个XML:

<org.mule.module.json.JsonData>
  <node class="org.codehaus.jackson.node.ObjectNode">
    <__nodeFactory/>
    <__children>
      <entry>
        <string>freshdesk_webhook</string>
        <org.codehaus.jackson.node.ObjectNode>
          <__nodeFactory reference="../../../../__nodeFactory"/>
          <__children>
            <entry>
              <string>ticket_id</string>
              <org.codehaus.jackson.node.IntNode>
                <__value>7097</__value>
              </org.codehaus.jackson.node.IntNode>
            </entry>
            <entry>
              <string>ticket_requester_email</string>
              <org.codehaus.jackson.node.TextNode>
                <__value>walter@white.com</__value>
              </org.codehaus.jackson.node.TextNode>
            </entry>
          </__children>
        </org.codehaus.jackson.node.ObjectNode>
      </entry>
    </__children>
  </node>
</org.mule.module.json.JsonData>

我需要使用XSLT将其转换为:

<root>
  <entry>
    <name>freshdesk_webhook</name>
    <value>
      <entry>
        <name>ticket_id</name>
        <value>7097</value>
      </entry>
      <entry>
        <name>ticket_requester_email</name>
        <value>walter@white.com</value>
      </entry>
    </value>
  </entry>
</root>

我相信转型很容易。但是我今天测试了许多XSLT并且还没有结果。如何使用递归XSLT将我繁重的XML转换为简单的XML?

请帮忙。

1 个答案:

答案 0 :(得分:3)

这是相当简单的,因为如果没有特定节点的明确匹配,XSLT的built in template rules元素只会继续处理子节点,而文本节点的默认规则只是输出文本。因此映射变为

  • 顶级文档元素 - &gt; root
  • entry - &gt; entry
  • 每个条目的第一个子元素 - &gt; name
  • 每个条目的第二个子元素 - &gt; value

而其他一切只使用默认的“与孩子同行”规则

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:strip-space elements="*" />
  <xsl:output indent="yes" />

  <xsl:template match="/*">
    <root><xsl:apply-templates /></root>
  </xsl:template>

  <xsl:template match="entry">
    <entry><xsl:apply-templates /></entry>
  </xsl:template>

  <xsl:template match="entry/*[1]">
    <name><xsl:apply-templates /></name>
  </xsl:template>

  <xsl:template match="entry/*[2]">
    <value><xsl:apply-templates /></value>
  </xsl:template>
</xsl:stylesheet>

xsl:strip-space很重要,因为它会导致样式表忽略输入XML中的所有缩进(仅限空格的文本节点),并且只关注元素和重要文本({{{{1}的内容。 1}}和string元素。)

相关问题