使用xsl转换xml

时间:2015-11-11 09:34:55

标签: xml xslt

我尝试使用具有多个属性的xml 女巫看起来像那样

  <AllNames name="John">
    <dates>
      <date day="20150126" country="uk" fruit="kiwi">PP</rank>
      <date day="20150227" country="uk" fruit="coconut">PP</rank>
    </dates>
  </AllNames>
  <AllNames name="Michael">
      <dates>
      <date day="20150126" country="uk" fruit="apple">XX</rank>
      <date day="20150127" country="uk" fruit="orange">YY</rank>
    </dates>
  </AllNames>

我想要我的结果 看起来像那样:

John,20150126,uk,kiwi,PP

John,20150227,英国,椰子,PP

迈克尔,20150126,英国,苹果,XX

迈克尔,20150127,英国,橙色,YY

我已经尝试了这个代码,dosnt工作,请帮助我

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text" />
<xsl:variable name="delimiter" select="','" />
<xsl:variable name="fieldArray">
    <field>name</field>
    <field>day</field>
    <field>country</field>
    <field>fruit</field>
  </xsl:variable>
  <xsl:param name="fields" select="document('')/*/xsl:variable[@name='fieldArray']/*" />

  <xsl:template match="/">
         <xsl:for-each select="$fields">
      <xsl:if test="position() != 1">
        <xsl:value-of select="$delimiter"/>
      </xsl:if>
      <xsl:value-of select="." />
    </xsl:for-each>
 <xsl:text>
</xsl:text>
  <xsl:apply-templates select="AllNames/name"/>
  </xsl:template>

  <xsl:template match="rank">
    <xsl:variable name="currNode" select="." />

    <xsl:for-each select="$fields">
      <xsl:if test="position() != 1">
        <xsl:value-of select="$delimiter"/>
      </xsl:if>
      <xsl:value-of select="$currNode/*[name() = current()]" />
    </xsl:for-each>
        <xsl:text>
</xsl:text>
  </xsl:template>
</xsl:stylesheet>

1 个答案:

答案 0 :(得分:2)

您的输入仍然不是格式良好的XML。如果你有一个输入,如:

<强> XML

<root>
   <entry name="John">
      <dates>
         <date day="20150126" country="uk" fruit="kiwi">AA</date>
         <date day="20150227" country="uk" fruit="coconut">BB</date>
      </dates>
   </entry>
   <entry name="Michael">
      <dates>
         <date day="20150126" country="uk" fruit="apple">XX</date>
         <date day="20150127" country="uk" fruit="orange">YY</date>
      </dates>
   </entry>
</root>

你可以使用:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/root">
    <xsl:for-each select="entry/dates/date">
        <xsl:value-of select="../../@name" />
        <xsl:text>,</xsl:text>
        <xsl:value-of select="@day" />
        <xsl:text>,</xsl:text>
        <xsl:value-of select="@country" />
        <xsl:text>,</xsl:text>
        <xsl:value-of select="@fruit" />
        <xsl:text>,</xsl:text>
        <xsl:value-of select="." />
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

得到:

John,20150126,uk,kiwi,AA
John,20150227,uk,coconut,BB
Michael,20150126,uk,apple,XX
Michael,20150127,uk,orange,YY