XLT格式化XML那点事(C#代码中的问题解决)(二)

接上篇《XML通过XSL格式化的那点事(XML到自定义节点折叠显示)》,本文就如何将大的XLST分割成小文件和如何用C#将XML通过XSL生成HTML文件中的问题做下分析,避免有同样需求的朋友走弯路。

Import的使用

<xsl:Import> 元素必须在第一个节点

image

image

如何避免输出SelfClose的非法元素

 

简单繁琐的办法

<script type="text/javascript" src="nowhere.js">
<xsl:comment></xsl:comment>
</script>

 

一劳永逸的方法

不用XMLWriter使用自己定义的XMLHTMLWriter

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Xml;

namespace XSLSelfClosing 
{ 
    public class XmlHtmlWriter : XmlTextWriter 
    { 
        public XmlHtmlWriter(System.IO.Stream stream, Encoding en) 
            : base(stream, en) 
        {

            //Put all the elemnts for which you want self closing tags in this list. 
            //Rest of the tags would be explicitely closed 
            fullyClosedElements.AddRange(new string[] { "br", "hr" }); 
        }

        string openingElement = ""; 
        List<string> fullyClosedElements = new List<string>();

        public override void WriteEndElement() 
        { 
            if (fullyClosedElements.IndexOf(openingElement) < 0) 
                WriteFullEndElement(); 
            else 
                base.WriteEndElement(); 
        } 

        public override void WriteStartElement(string prefix, string localName, string ns) 
        { 
            base.WriteStartElement(prefix, localName, ns); 
            openingElement = localName; 
        } 
    } 
}

 

XSL Copy 函数会为节点自动添加xmlns的问题

解决方法:

添加如下模板

<xsl:template match="*" mode="copy-no-namespaces">
    <xsl:element name="{local-name()}">
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates select="node()" mode="copy-no-namespaces"/>
    </xsl:element>
</xsl:template>

<xsl:template match="comment()| processing-instruction()" mode="copy-no-namespaces">
    <xsl:copy/>
</xsl:template>

 

应用示例,替换掉使用`Copy-of`的代码段

<xsl:apply-templates select="$var1_SCTIcfBlkCredTrf/ns0:FIToFICstmrCdtTrf/sw8:CdtTrfTxInf" mode="copy-no-namespaces"/>

 

参考

XSLT self-closing tags issue

How to force Non-Self Closing tags for empty nodes when using XslCompiledTransform class

How to mimic copy-namespaces=“no” in XSLT 1.0?

原文地址:https://www.cnblogs.com/HQFZ/p/4798652.html