使用XSL删除XML中的空属性

时间:2016-02-29 21:34:28

标签: xml xslt

我已阅读多篇文章,但没有一个答案有助于解决我的问题。

我有一个XML文档,其中一个属性是可选的(考试?):

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="college.xsl" ?>
<College>
  <School>Information Technology</School>
  <Program>Computer Programmer</Program>
  <Course Code="TECH6200">
    <Location>SW202</Location>
    <Day>Tuesday</Day>
    <Duration>8-10am</Duration>
    <Teacher>Devi Ambati</Teacher>
    <Teacher>Darren Puffer</Teacher>
    <Units>4</Units>
    <Coursework>60</Coursework>
    <Exam>40</Exam>
  </Course>
  <Course Code="DBAS6303">
    <Location>H133</Location>
    <Day>Wednesday</Day>
    <Duration>10am-12pm</Duration>
    <Teacher>Kevin D</Teacher>
    <Units>4</Units>
    <Coursework>100</Coursework>
  </Course>
  <Course Code="PROG4208">
    <Location>H166C</Location>
    <Day>Monday</Day>
    <Duration>12-2pm</Duration>
    <Teacher>Kevin D</Teacher>
    <Units>3</Units>
    <Coursework>100</Coursework>
  </Course>
</College>

然后我有我的XSL文档。如果Exam %:标记中没有<Exam></Exam>标记,我想将其切换为不显示<Course></Course>

<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
    <b>School:</b>&#160;<xsl:value-of select="College/School"/><br/>
    <b>Program:</b>&#160;<xsl:value-of select="College/Program"/><br/><br/>
    <xsl:for-each select="College/Course">
      <div style="background-color:teal;color:white;padding:4px">
        <xsl:value-of select="@Code"/>
      </div>
      <div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
        <p>
          <b>Location:</b>&#160;<xsl:value-of select="Location"/><br/>
          <b>Day:</b>&#160;<xsl:value-of select="Day"/><br/>
          <b>Duration:</b>&#160;<xsl:value-of select="Duration"/><br/>
          <xsl:for-each select="Teacher">
            <b>Teacher:</b>&#160;<xsl:value-of select="."/><br/>
          </xsl:for-each>
          <b>Units:</b>&#160;<xsl:value-of select="Units"/><br/>
          <b>Course Work %:</b>&#160;<xsl:value-of select="Coursework"/><br/>
          <b>Exam %:</b>&#160;<xsl:value-of select="Exam"/>
        </p>
      </div>
    </xsl:for-each>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

您可以在测试中包含Exam值的用法以显示它:

...
<xsl:if test="Exam">
  <b>Exam %:</b>&#160;<xsl:value-of select="Exam"/>
</xsl:if>
...