XPath屬性節點

2019-10-16 23:18:18

可以使用元素的@attribute-name來檢索和檢查此屬性。

@name - 獲取屬性name的值。

<td><xsl:value-of select = "@rollno"/></td>

屬性可用於使用運算子進行比較。

@rollno = 493 - 獲取屬性rollno的文字值並與值進行比較。

<xsl:if test = "@rollno = 493">

範例

在這個例子中,我們建立了一個範例XML文件students.xml,及其樣式表文件students.xsl,它使用了XPath表示式。

以下是使用的範例XML,檔案:students.xml -

<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
   <student rollno = "393">
      <firstname>Dinkar</firstname>
      <lastname>Su</lastname>
      <nickname>MaXX</nickname>
      <marks>88</marks>
   </student>
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Lee</lastname>
      <nickname>Vicky</nickname>
      <marks>95</marks>
   </student>
   <student rollno = "593">
      <firstname>Jasvir</firstname>
      <lastname>Wong</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>

檔案:students.xsl -

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

   <xsl:template match = "/">
      <html>
         <body>
            <h3>每個學生的詳細資訊,Xpath表示式 = "/class/student"</h3>

            <table border = "1">
               <tr bgcolor = "#9acd32">
                  <th>Roll No</th>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Nick Name</th>
                  <th>Marks</th>
               </tr>

               <xsl:for-each select = "/class/student">
                  <tr>
                     <td><xsl:value-of select = "@rollno"/></td>
                     <td><xsl:value-of select = "firstname"/></td>
                     <td><xsl:value-of select = "lastname"/></td>
                     <td><xsl:value-of select = "nickname"/></td>
                     <td><xsl:value-of select = "marks"/></td>
                  </tr>
               </xsl:for-each>
            </table> 

            <h3>`rollno`為`493`的學生的詳細資訊,Xpath表示式 = "@rollno = 493"</h3>

            <table border = "1">
               <tr bgcolor = "#9acd32">
                  <th>Roll No</th>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Nick Name</th>
                  <th>Marks</th>
               </tr>

               <xsl:for-each select = "//student">

                  <xsl:if test = "@rollno = 493">
                     <tr>
                        <td><xsl:value-of select = "@rollno"/></td>
                        <td><xsl:value-of select = "firstname"/></td>
                        <td><xsl:value-of select = "lastname"/></td>
                        <td><xsl:value-of select = "nickname"/></td>
                        <td><xsl:value-of select = "marks"/></td>
                     </tr>
                  </xsl:if>
               </xsl:for-each>
            </table> 
         </body>
      </html>
   </xsl:template>
</xsl:stylesheet>

使用瀏覽器開啟student.xml ,效果如下所示 -