创建循环遍历XML的XSL文件

时间:2013-09-11 04:32:58

标签: xml loops xslt

我正在尝试创建一个循环遍历此XML文件的XSL文件。

XML:

<ArrayOfCourse xmlns="http://schemas.datacontract.org/2004/07/Demo.Samples" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Course>
<codeField>COMPSCI 101</codeField>
<semesterField>Summer School; Semester 1; Semester 2</semesterField>
<titleField>Principles of Programming</titleField>
</Course>
</ArrayOfCourse>

这就是我提出的,如果我将ArrayOfCourse标记更改为<ArrayOfCourse>(删除xmlns),这可以正常工作。

XSL:

<?xml version="1.0"?>
    <xsl:stylesheet version="1.0"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

      <xsl:template match="/">
        <HTML>
          <BODY>
              <xsl:for-each select="ArrayOfCourse/Course">
                <xsl:sort select="state" order="descending"/>
                <xsl:sort select="name"/>
                <xsl:value-of select="codeField" />:
                <b><xsl:value-of select="titleField" /> </b><br/>
                <xsl:value-of select="semesterField" /> <br/><br/>
              </xsl:for-each>
          </BODY>
        </HTML>
      </xsl:template>

    </xsl:stylesheet>

如果仍然在代码中使用xmlns="..."部分,我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

由于您使用的是XSLT 1.0,因此您需要:

  • 使用前缀声明命名空间并在xpath中使用前缀。 (推荐

  • 在谓词中使用local-name()namespace-uri()(可选)。 (例如:*[local-name()='Course']

使用前缀ds声明的命名空间的XSLT示例(前缀可以是任何内容,不需要与输入中的前缀匹配(如果有的话)):

<xsl:stylesheet version="1.0"
    xmlns:ds="http://schemas.datacontract.org/2004/07/Demo.Samples"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

    <xsl:template match="/">
        <HTML>
            <BODY>
                <xsl:for-each select="ds:ArrayOfCourse/ds:Course">
                    <xsl:sort select="ds:state" order="descending"/>
                    <xsl:sort select="ds:name"/>
                    <xsl:value-of select="ds:codeField" />:
                    <b><xsl:value-of select="ds:titleField" /> </b><br/>
                    <xsl:value-of select="ds:semesterField" /> <br/><br/>
                </xsl:for-each>
            </BODY>
        </HTML>
    </xsl:template>

</xsl:stylesheet>

Google xslt default namespace了解更多信息。

相关问题