跳至內容

XForms/使用 XSLT 排序

來自華夏公益教科書

使用 XForms 建立表單時,一個反覆出現的問題是缺乏排序功能。這是一個在 Firefox 中使用 XSLT 樣式表對例項進行排序的示例。

Firefox XForms 示例

[編輯 | 編輯原始碼]

以下模型包含兩個例項。第一個例項是我們將要排序的例項,第二個例項包含我們將用於執行排序的 XSLT 樣式表。

<xf:model>
  <xf:instance id="default-instance">
    <data xmlns="">
      <item>
        <name>B-item</name>
        <date>2001-05-03</date>
      </item>
      <item>
        <name>A-item</name>
        <date>2005-05-03</date>
      </item>
      <item>
        <name>Z-item</name>
        <date>2003-05-03</date>
      </item>
      <item>
        <name>D-item</name>
        <date>2002-05-03</date>
      </item>
    </data>
  </xf:instance>

  <xf:instance id="stylesheet">
    <xsl:stylesheet
      xmlns="" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
      version="1.0">
      <xsl:template match="/">
        <data>
          <xsl:apply-templates select="data/item">
            <xsl:sort type="string" select="name"/>
          </xsl:apply-templates>
        </data>
      </xsl:template>
      <xsl:template match="*|@*|text()">
        <xsl:copy>
          <xsl:apply-templates select="*|text()|@*"/>
        </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>
  </xf:instance>
</xf:model>

為了執行排序,我們將使用以下 JavaScript 程式碼。它將把第二個例項載入到 Firefox 樣式表引擎中,然後獲取第一個例項,進行轉換,生成排序後的例項。然後,將轉換後的例項插入模型,並執行重建、重新計算、重新驗證和重新整理操作。

function sort_instance(id) {
  // We get the instance element
  var instanceElement = document.getElementById(id);
  if (instanceElement!=null) {

   // XForms exposes the retrival of the instance document from the model element which *should*
   // be the parent for the instance element.
   var instance = instanceElement.parentNode.getInstanceDocument(id);

   if (instance!=null) {
      // Now creating the stylesheet, for this example the stylesheet document is also an instance
      // but it can be loaded from many difference sources
      var xslDom = instanceElement.parentNode.getInstanceDocument('stylesheet');

      // create an XSLTProcessor and attach the stylesheet
      var processor = new XSLTProcessor()
      processor.importStylesheet(xslDom);

      // now we do the sorting transformation
      var resultDom = processor.transformToDocument(instance, instance);

      // we then move the result info the instance dom
      instance.removeChild(instance.documentElement);
      instance.appendChild(resultDom.documentElement);

      // and performs the updates for XForms
      instanceElement.parentNode.rebuild();
      instanceElement.parentNode.recalculate();
      instanceElement.parentNode.revalidate();
      instanceElement.parentNode.refresh();
    }
  }
}

將樣式表放在一個例項中,可以透過繫結控制元件來更改排序行為,並更改 XPath 表示式和其他 XSLT 語法等內容。

參考文獻

[編輯 | 編輯原始碼]

此示例基於 [[1]http://landwehr.dk/blog/] 上的示例。


下一頁: 移動 XForms | 上一頁: Google 地圖
首頁: XForms
華夏公益教科書