2008-12-23 55 views
3

我喜歡.NET的webcontrols和你操縱的東西,這是共識,但XML和XSL是如此之大,因爲你的UI邏輯是平臺&語言無關,所以有一天我將應用程序更改爲PHP,Java或任何我可以重用所有的表示邏輯。另外,XSL可以在渲染之前調用.NET(或其他)方法。何時使用xml而不是HTML使用xsl?

什麼時候通常使用XML/XSL?爲什麼不能更頻繁地使用它?

回答

2

而不是HTML?

我經常使用它來代替asp.net控件,因爲它提供了對2.0和V中的關注點的分離,您不會在.NET 2.0中獲得開箱即用的功能。

顯然有一百萬與asp.net控件無關的其他用途。


編輯:實現

public class xsltmanager 
{ 
    /* constructor (singleton) which defines a file watcher for *.xsl in the path of your choice */ 

    //just a mutex for thread safety 
    private object Mutex = new object(); 

    //caching XslCompiledTransforms 
    private Dictionary<string, XslCompiledTransform> cTransforms = new Dictionary<string, XslCompiledTransform>(); 

    public XslCompiledTransform fetch(string identifier) 
    {  
     if (!this.cTransforms.ContainsKey(identifier)) 
     { 
      lock (this.Mutex) 
      { 
       if (!this.cTransforms.ContainsKey(identifier)) 
       { 
        XslCompiledTransform xslDoc = new XslCompiledTransform(); 
        xslDoc.Load(/* file path based on identifier */); 

        this.cTransforms.Add(identifier, xslDoc); 
       } 
      } 
     } 
     return this.cTransforms[identifier]; 
    } 

    /* other util xslt methods - namespace wash, doc merge, whatever */ 
} 

public class myPage : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     //get source data 
     XPathDocument xPathDoc = myGetXMLMethod(); 

     //transform params 
     XsltArgumentList oArgs = new XsltArgumentList(); 

     /* add params as required */ 

     //fetching and executing the transform directly to the Response here 
     xsltmanager.instance.get(@"foo\bar\baz").Transform(xPathDoc, oArgs, Response.OutputStream); 
    } 
} 
+0

你如何將它與.NET集成? – netadictos 2008-12-23 11:31:42

+0

本質上只是在代碼隱藏中針對Response.OutputStream進行轉換。 – annakata 2008-12-23 12:09:25

1

沒有那麼多在ASP.NET的東西,但在此之前(與VB6)我曾幾乎完全(在服務器)使用它來將XML轉換爲HTML。我一直髮現它非常靈活。我也將其作爲代碼生成器引擎在我的「protocol buffers」項目中使用:主框架生成xml,然後使用xsl轉換來吐出C#。我聽說有人說他們沒有找到直觀的xsl,但我真的很喜歡它,並且它是處理xml時的默認工具。

現在,我正在尋找很多ASP.NET MVC,它並不一定適用於xsl - 儘管在某些方面,<%=foo.Name%><xsl:value-of select="Name"/>之間沒有太大的區別。

-3

有使用XML/XSL巨大的開銷,也有很多缺點的草圖。

  1. 您需要一個完整的XML數據集來確保XSL僅用作邏輯引擎。
  2. 其次,XSL邏輯控制較差,版本間不一致。
  3. 三,組合是一個相當繁重的過程,不適合大型網站。

如果您關心邏輯分離,請使用一些模板語言(不是XSL)。

2

第一個近似值,無論何時我需要將信息呈現爲HTML,我都會使用XSLT。幾乎每次我在過去七年中都偏離了這一點,我都很後悔。我在Python中使用HTML生成的簡短經驗是我遇到的唯一可能可以替代它的東西。