Skip to main content
 首页 » 编程设计

c#之XSLT 转换创建 StackoverflowException

2024年02月24日25wuhuacong

我尝试对 XSD 文件执行 XSLT 转换。我的最终目标是从 XSD 创建 SQL。到目前为止一切顺利,这就是我所拥有的:

void Convert() 
{ 
            XPathDocument xpathDoc = new XPathDocument(@"myschema.xsd"); 
            string xslPath = @"convert.xsl"; 
            XslCompiledTransform transform = new XslCompiledTransform();                
            transform.Load(xslPath, new XsltSettings(true, true), null);     
            using (FileStream fs = File.Create(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "output.sql"))) 
            { 
                try 
                { 
                    transform.Transform(xpathDoc, null, fs); 
                } 
                catch 
                { 
                    fs.Close(); 
                } 
            } 
} 

这是失败的 XSLT 文件:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
               version="1.0"  
               xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
 
<!-- Get schema nodes from this schema and any included schemas --> 
<xsl:variable name="contents" select="/|document(//xs:include/@schemaLocation)" /> 
 
<xsl:template match="*" > 
 
 <xsl:for-each select="$contents" > 
  <xsl:apply-templates select=".//xs:element" /> 
 </xsl:for-each> 
 
</xsl:template> 
 
<xsl:template match="xs:element"> 
 
    <xsl:apply-templates /> 
 
</xsl:template> 
 
</xsl:stylesheet> 

我总是在 System.Data.SqlXml.dll 中得到 StackoverflowException。我怎样才能停止递归?没有 xs:element 是不是应该停止?

编辑: 原始代码来自 here它已经有错误了。我尝试通过简化 XSLT 来修复它,直到只剩下错误。

请您参考如下方法:

这条线

<xsl:apply-templates select=".//xs:element" /> 

将当前节点 (xs:element) 发送到它开始的模板。然后它在for循环中匹配它并再次发送自己。堆栈溢出是不可避免的。