c# - 将 XSLT 中的模板附加到另一个 XSLT

标签 c# xml xslt

我在使用 C# 的 Visual Studio 2012 中工作。 我有两个 xslt 文件。 一个有几个模板。 另一个在那里定义了一些节点。 我想要的只是在 C# 中构建一个函数,使用它传递模板名称。它使用该名称在一个 xslt 中搜索,如果存在具有给定名称的模板,它会将其复制到第二个 xslt 中。

F("GetMonth") 的结果应该如下:

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

请提出建议。

最佳答案

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

关于c# - 将 XSLT 中的模板附加到另一个 XSLT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22221177/

相关文章:

c# - 为什么类型推断和隐式运算符在以下情况下不起作用?

java - 在 javax.xml.transform.Transformer 中处理原始文本

android - 什么是android :ems in android application design

java - 获取一个 XML 文件和一个 XSL 文件并从中生成一个 HTML 字符串?

javascript - Node JS、Cheerio、获取 XML 版本

xml - 合并两个 XML 文件

c# - 跟踪按钮点击次数

c# - 在 C# 中处理窗体上的控件时何时使用 THIS 关键字

c# - 在 Visual Studio 2012 中保存测试

xslt - 条件 AND OR 两个不同的值