每个循环中的每个循环中的每个循环的XSLT for for

时间:2015-10-13 13:34:58

标签: xml xslt

您好我想使用xslt将source.xml更改为destination.xml但我的代码无效。请帮助

source.xml

<Programme>
  <SubjectList>
    <Subject>Maths</Subject>
    <Subject>Science</Subject>
    <Subject>History</Subject>
    <Subject>Language</Subject>
  </SubjectList>

  <StudentList>
    <Student>
      <Name>Jack</Name>
      <Class>5</Class>
      <Subjects>
        <Course>Maths</Course>
        <Course>Language</Course>
      </Subjects>
    </Student> 
    <Student>
      <Name>John</Name>
      <Class>4</Class>
      <Subjects>
        <Course>Maths</Course>
        <Course>Science</Course>
      </Subjects>
    </Student>
    <Student>
      <Name>Anna</Name>
      <Class>4</Class>
      <Subjects>
        <Course>Science</Course>
        <Course>History</Course>
      </Subjects>
    </Student>

    <Student>
      <Name>Tana</Name>
      <Class>5</Class>
      <Subjects>
        <Course>History</Course>
        <Course>Language</Course>
      </Subjects>
    </Student>
  </StudentList>
</Programme>

destination.xml

<ProgramList> 
  <Subject>
    <title>Maths</title>
    <Students>
      <Name>Jack</Name>
      <Name>John</Name>
    <Students>
  </Subject>

  <Subject>
    <title>Science</title>
    <Students>
      <Name>John</Name>
      <Name>Anna</Name>
    <Students>
  </Subject>

  <Subject>
    <title>History</title>
    <Students>
      <Name>Anna</Name>
      <Name>Tana</Name>
    <Students>
  </Subject>

  <Subject>
    <title>Language</title>
    <Students>
      <Name>Jack</Name>
      <Name>Tana</Name>
    <Students>
  </Subject> 
</ProgramList>

这是我的xslt,但它不起作用,我对xslt非常新,请帮助。

<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:template match="/">
<subjects>
    <xsl:for-each select="SubjectList/Subject">
      <xsl:variable name="var1" select="."/>
      <subject>
      <title><xsl:value-of select="text()"/></title>
        <xsl:for-each select="StudentList/Student">
            <xsl:variable name="student" select="."/>
            <xsl:for-each select="Subjects/Course">     
            <xsl:variable  name="var2">
            <xsl:value-of select="."/>
            </xsl:variable>             
                <xsl:if  test= "$var2=$var1">
                <student>
                    <name><xsl:value-of select="$student/Name"/></name>
                    <class><xsl:value-of select="$student/Class"/></class>
                </student>
                </xsl:if>
        </xsl:for-each>
        </xsl:for-each>
        <subject>
    <xsl:value-of select="$newline"/>
    </xsl:for-each>
</subjects>

</xsl:template>
</xsl:stylesheet>

1 个答案:

答案 0 :(得分:0)

路径表达式StudentList/Student的上下文是Subject元素,但您的Subject元素没有StudentList子元素。您需要先上升几个级别:../../StudentList/Student。但更好的是,对于此类问题,请阅读xsl:keykey()函数。