2014-03-06 38 views
2

我正在使用C#在Visual Studio 2012中工作。 我有兩個xslt文件。 一個有幾個模板。 另一個在那裏定義了一些節點。 我想要的只是在C#中使用它傳遞模板名稱來構建一個函數。使用該名稱在一個xslt中搜索,並且如果存在具有給定名稱的模板,則將其複製到第二個xslt中。將模板從XSLT追加到另一個XSLT中

F( 「得到月」)應該產生如下:

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

<xsl:template name="GetMonth"> 
    <xsl:param name="Month"/> 
    <xsl:param name="PutCall"/> 
    <xsl:value-of select ="'A'"/> 
</xsl:template> 

XSLT2: 
<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/"> 
    <DocumentElement> 
// Some Code written 
    </DocumentElement> 
</xsl:template> 
</xsl:stylesheet> 

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

<xsl:template name="GetMonth"> 
    <xsl:param name="Month"/> 
    <xsl:param name="PutCall"/> 
    <xsl:value-of select ="'A'"/> 
</xsl:template> 

<xsl:template match="/"> 
    <DocumentElement> 
    // Some Tags defined here 
    </DocumentElement> 
</xsl:template> 
</xsl:stylesheet> 

我嘗試:

XmlDocument xslDoc1 = new XmlDocument(); 
XmlDocument xslDoc2 = new XmlDocument(); 
xslDoc1.Load("XSLT1.xslt"); 
xslDoc2.Load("XSLT2.xslt"); 

XmlNamespaceManager nsMg1r = new XmlNamespaceManager(xslDoc1.NameTable); 
nsMgr1.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform"); 

XmlNamespaceManager nsMgr2 = new XmlNamespaceManager(xslDoc2.NameTable); 
nsMgr2.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform"); 

XmlNodeList template = (XmlNodeList)xslDoc.SelectNodes("/xsl:stylesheet/xsl:template[@name = templateName]", nsMgr); 
if(template != null) 
{ 
// What code should be written here??? 
} 

請建議。

+0

請不要包含關於問題標題中使用的語言的信息,除非在沒有它的情況下沒有意義。標籤用於此目的。 –

+0

只是一個簡單的觀察:XSLT導入/包含指令可能會滿足您的需求,而無需對樣式表進行編程編輯。 – keshlam

+0

究竟如何?請給我一個例子。 – user3219897

回答

1
string templateName = "GetMonth"; 

XmlNode template = xslDoc.SelectSingleNode(string.Format("/xsl:stylesheet/xsl:template[@name = '{0}']", templateName), nsMgr); 

if (template != null) 
{ 
    // will append the template as last child of xsl:stylesheet 
    xslDoc2.DocumentElement.AppendChild(xslDoc2.ImportNode(template, true)); 
    // as alternative to insert as the first child use 
    // xslDoc2.DocumentElement.InsertBefore(xslDoc2.ImportNode(template, true), xslDoc2.DocumentElement.FirstChild); 
    // now Save 
    xslDoc2.Save("XSLT2.xslt"); 
} 
+0

它似乎並沒有工作! – user3219897

+0

會發生什麼,如果有錯誤,你會得到一個錯誤,哪一個?或者結果不是想要的?然後解釋你得到的結果。 –

+0

結果不是我想要的。它不會在現有的xslt文件中附加模板。 – user3219897