如何将自定义XML转换为Ruby ActiveResource XML格式

时间:2011-06-17 21:20:39

标签: xml xslt

我是XSLT的新手,请帮忙。 我们有一个XML,我们想将它转换为Ruby ActiveResource格式的XML。请帮我解决XSLT代码。谢谢。

XML INPUT

<PARM>
<PC>0</PC>
<PMT NM="THEME" DN="THEME" IR="0" T="0">
    <PV V="fast" L="" H="" C="4"/>
</PMT>
<PMT NM="INGREDIENTS" DN="INGREDIENTS" IR="0" T="0">
    <PV V="chicken" L="" H="" C="5"/>
    <PV V="tomato" L="" H="" C="12"/>
</PMT>
</PARM>

所需的XML输出

<facet-groups type="array">
 <facet-group>
  <name>THEME</name>
  <facets type="array">
    <facet>
      <name>fast</name>
      <count>4</count>
    </facet>
  </facets>
 </facet-group>
 <facet-group>
  <name>INGREDIENTS</name>
  <facets type="array">
    <facet>
      <name>chicken</name>
      <count>5</count>
    </facet>
    <facet>
      <name>tomato</name>
      <count>12</count>
    </facet>
  </facets>
 </facet-group>
</facet-groups>

请帮忙。谢谢。

2 个答案:

答案 0 :(得分:2)

正如@Keoki所说,在你给出一个完整的解决方案之前,你应该展示你所做的更多。但要开始,你会创建

  • 匹配“PARM”的模板,输出facet-groups元素,并在其中将模板应用于儿童

  • 匹配“PMT”的模板,输出facet-group元素,子项为<name><facets>,后者将模板应用于子项

  • 匹配“PV”的模板,输出facet个元素,其子项为<name><count>

希望这会给你一个良好的开端。

答案 1 :(得分:2)

换句话说,这是@LarsH:

<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="PARM">
        <facet-groups type="array">
            <xsl:apply-templates select="PMT"/>
        </facet-groups>
    </xsl:template>

    <xsl:template match="PMT">
        <facet-group>
            <name><xsl:value-of select="@NM"/></name>
            <facets type="array">
                <xsl:apply-templates select="PV"/>
            </facets>
        </facet-group>
    </xsl:template>

    <xsl:template match="PV">
        <facet>
            <name><xsl:value-of select="@V"/></name>
            <count><xsl:value-of select="@C"/></count>
        </facet>
    </xsl:template>

</xsl:stylesheet>