C#从XSLT删除整个节点

时间:2019-02-12 05:53:01

标签: c# asp.net .net xml xslt

从C#代码中,我想从XSLT删除节点。

例如。我在XSLT以下

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:template name="URLSpliter">
    <xsl:param name="url" />
    <xsl:variable name="splitURL" select="substring - after($url, '/')" />
    <xsl:if test="contains($splitURL, '/')">
      <xsl:call-template name="URLSpliter">
        <xsl:with-param name="url" select="$splitURL" />
      </xsl:call-template>
    </xsl:if>
    <xsl:if test="not(contains($splitURL, '/'))">
      <xsl:value-of select="$splitURL" />
    </xsl:if>
  </xsl:template>
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />

在这里,我要删除整个urlsplitter节点和URLSplitter中的所有节点

整个<xsl:template name="URLSpliter"> ...</template>应该被删除(+该特定节点内的所有节点)

2 个答案:

答案 0 :(得分:1)

您可以使用linq到xml并将其删除,如下所示

 documentRoot
           .Descendants("template")
           .Where(ele=> (string) ele.Attribute("name") == "URLSpliter")
           .Remove();

工作示例:

XElement documentRoot  = 
              XElement.Parse (@"<ordersreport date='2012-08-01'>
                             <returns>
                              <template name='URLSpliter'>
                              </template>
                              <amount>

                                  <orderid>2</orderid>             
                                  <orderid>3</orderid>
                                  <orderid>21</orderid>
                                  <orderid>23</orderid>
                               </amount>
                             </returns>
                        </ordersreport>");
                documentRoot
               .Descendants("template")
               .Where(ele=> (string) ele.Attribute("name") == "URLSpliter")
               .Remove();


            Console.WriteLine(documentRoot.ToString());

答案 1 :(得分:1)

这段代码将为您服务。只需相应地替换路径即可。

string xsltPath = @"C:\Users\ankushjain\Documents\Visual Studio 2017\Projects\ConsoleApp1\ConsoleApp1\XSLTFile.xslt";
string pathToSave = @"C:\Users\ankushjain\Documents\Visual Studio 2017\Projects\ConsoleApp1\ConsoleApp1\{0}.xslt";

XmlDocument xslDoc = new XmlDocument();
xslDoc.Load(xsltPath);

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

var nodesToDelete = xslDoc.SelectNodes("//xsl:template[@name='URLSpliter']", namespaceManager);

if (nodesToDelete != null & nodesToDelete.Count > 0)
{
    for (int i = nodesToDelete.Count - 1; i >= 0; i--)
    {
        nodesToDelete[i].ParentNode.RemoveChild(nodesToDelete[i]);
    }
    xslDoc.Save(string.Format(pathToSave, Guid.NewGuid()));
}