我正在使用C#转换XML文档,它运行良好:
<p>
Server current time at point of page rendering:
<input type="text" id="ServerTime" value="@DateTime.UtcNow.ToString("s")"/>
</p>
<p>
My object's date time:
<input type="text" id="EntityTime" value="@DateTime.UtcNow.AddSeconds(-30).ToString("s")" />
</p>
<div id="Output"></div>
<script>
var output = document.getElementById("Output");
var serverTime = Date.parse(document.getElementById("ServerTime").value);
var entityTime = Date.parse(document.getElementById("EntityTime").value);
var staticDifference = (serverTime - entityTime) / 1000;
output.innerHTML += "Static difference between two entities: " + staticDifference + " seconds.<br/>";
var offset = serverTime - new Date().getTime();
function calculateDateTime() {
var commonTime = new Date().getTime() + offset;
var calculatedDifference = (commonTime - entityTime) / 1000;
output.innerHTML += "Posted " + calculatedDifference + " seconds ago.<br/>";
}
setInterval(calculateDateTime, 3000);
</script>
上面的代码完美无缺,但是我想要做的是,在转换XSLT之前,我希望它为XSLT的特定部分添加额外的代码行。
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>");
}
}
我希望如何在C#中更改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>
如何实现这一目标?
答案 0 :(得分: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")));