在转换之前向XSLT添加代码

本文关键字:XSLT 添加 代码 转换 | 更新日期: 2023-09-27 18:02:08

我正在使用c#转换XML文档,它工作得很好:

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>

如何在c#中更改XSLT代码在转换之前:

<?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>

如何做到这一点?

在转换之前向XSLT添加代码

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")));