用于WTF“良好形成”的xsl变换示例

时间:2010-08-23 19:34:07

标签: xml xslt

当我在Daily WTF上阅读这篇文章时,我大声笑了起来:http://thedailywtf.com/Articles/WellFormed-XML.aspx,但现在它已经不再有趣了,因为我已经开始以惊人的频率在野外认识到这种“xml设计模式”。例如,我刚从理性clearquest查询中导出了一些数据,我得到了这个:

<?xml version="1.0" encoding="us-ascii"?>
<?xml-stylesheet type="text/xsl" href="http://scm/rational/clearquest/webservice/resultset.xsl"?>
<resultset dbset="CQMaster" dbname="PROD" entitydefname="TR" count="1" name="_my trs">
  <header count="3">
    <column type="dbid">dbid</column>
    <column type="id">id</column>
    <column type="short_string">Abstract</column>
  </header>
  <record>
    <field>33607697</field>
    <field>PROD00011111</field>
    <field>The product has a bug that needs fixed.</field>
  </record>
</resultset>

我不是一个xslt向导 - 我可能迟早会弄清楚这一点,但是问一下...最简单的xslt模式将上面的内容转换成更有用的东西是这样的:

<?xml version="1.0" encoding="us-ascii"?>
<resultset dbset="CQMaster" dbname="PROD" entitydefname="TR" count="1" name="_my trs">
  <record>
    <dbid type="dbid">33607697</dbid>
    <id type="id">PROD00011111</id>
    <Abstract type="short_string">The product has a bug that needs fixed.</Abstract>
  </record>
</resultset>

1 个答案:

答案 0 :(得分:1)

以下转型

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

 <xsl:key name="kColByPos" match="column"
  use="count(preceding-sibling::*) +1"/>

 <xsl:template match="/*">
  <xsl:copy>
   <xsl:copy-of select="@*"/>
   <xsl:apply-templates select="record"/>
  </xsl:copy>
 </xsl:template>

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

 <xsl:template match="field">
  <xsl:variable name="vColumn" select=
   "key('kColByPos', position())"/>

   <xsl:element name="{translate($vColumn, ' ', '_'}">
    <xsl:copy-of select="$vColumn/@type"/>
    <xsl:apply-templates/>
   </xsl:element>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<resultset dbset="CQMaster" dbname="PROD" entitydefname="TR" count="1" name="_my trs">
  <header count="3">
    <column type="dbid">dbid</column>
    <column type="id">id</column>
    <column type="short_string">Abstract</column>
  </header>
  <record>
    <field>33607697</field>
    <field>PROD00011111</field>
    <field>The product has a bug that needs fixed.</field>
  </record>
</resultset>

生成想要的正确结果

<resultset dbset="CQMaster" dbname="PROD" entitydefname="TR" count="1" name="_my trs">
    <record>
        <dbid type="dbid">33607697</dbid>
        <id type="id">PROD00011111</id>
        <Abstract type="short_string">The product has a bug that needs fixed.</Abstract>
    </record>
</resultset>