2015-07-10 56 views
0

之前,我使用C#来转换XML文档,它是工作的罚款:到XSLT添加代码转换

using System; 
using System.IO; 
using System.Xml; 
using System.Xml.Xsl; 
using System.Xml.XPath; 

public class XmlTransformUtil 
{ 

public static void Main(string[] args) 
{ 

    if (args.Length == 2) 
    { 

     Transform(args[0], args[1]); 
    } 
    else 
    { 

     PrintUsage(); 
    } 
} 

public static void Transform(string sXmlPath, string sXslPath) 
{ 
    try 
    { 
     //load the Xml doc 
     XPathDocument myXPathDoc = new XPathDocument(sXmlPath); 

     XslTransform myXslTrans = new XslTransform(); 

     //load the Xsl 
     myXslTrans.Load(sXslPath); 

     //create the output stream 
     XmlTextWriter myWriter = new XmlTextWriter 
      ("result.html", null); 

     //do the actual transform of Xml 
     myXslTrans.Transform(myXPathDoc, null, myWriter); 

     myWriter.Close(); 
    } 

    catch (Exception e) 
    { 
     Console.WriteLine("Exception: {0}", e.ToString()); 
    } 
} 

public static void PrintUsage() 
{ 
    Console.WriteLine 
    ("Usage: XmlTransformUtil.exe <xml path> <xsl path>"); 
} 

} 

上面的代码完美的作品,但我想要做的是,之前的XSLT是我希望它将额外的代码行添加到XSLT的特定部分。

XSLT代码:

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

<xsl:template match="/"> 
    <html lang="en-GB"> 
     <body style="font-family:'Praxis Com Light'; color:#632423; width:100%; font-size:14px !important;"> 

//MAIN BODY OF CODE 

     </body> 
    </html> 
</xsl:template> 
</xsl:stylesheet> 

如何我想要的XSLT代码在C#中改变了改造前:

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:include href="HEAD.xslt"/> 
<xsl:include href="FOOT.xslt"/> 

<xsl:template match="/"> 
    <html lang="en-GB"> 
     <body style="font-family:'Praxis Com Light'; color:#632423; width:100%; font-size:14px !important;"> 

     <xsl:call-template name="Header"/> 

//MAIN BODY OF CODE 

      <xsl:call-template name="Footer"/> 

      </body> 
     </html> 
    </xsl:template> 
</xsl:stylesheet> 

这又如何实现呢?

+2

看起来不是将参数传递给变换,而是关闭它。示例 - http://stackoverflow.com/questions/1521064/passing-parameters-to-xslt-stylesheet-via-net – OldProgrammer

+0

不知道什么是困难。一个XSLT样式表是一个XML文档,您有一个用于转换XML文档的工具(XSLT),所以就这样做。无论是转换样式表在这里都是正确的策略,我不知道(这是一种强大的技术,但有时候其他方式会更好),但从本质上讲,如果您想使用XSLT来转换XSLT,那就没有问题了。 –

回答

1
XNamespace ns = "http://www.w3.org/1999/XSL/Transform"; 

XElement xslt = XElement.Load(sXslPath); 

xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", "FOOT.xslt"))); 
xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", "HEAD.xslt"))); 

XElement body = xslt.Descendants("body").Single(); 

body.AddFirst(new XElement(ns + "call-template", new XAttribute("name", "Header"))); 
body.Add(new XElement(ns + "call-template", new XAttribute("name", "Footer"))); 
+0

我认为你需要使用'XElement xslt = XElement.Load(xXslPath,LoadOptions.SetBaseUri)'来正确解析新添加的'xsl:include'。 –