1

我正在使用 .NET 框架 3.5 中提供的 XslCompiledTransform 类将我的 XML 文件转换为另一个 XML 文件

这是我的代码。

private static void transformUtil(string sXmlPath, string sXslPath, string outputFileName)
    {
        try
        {

            XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
            XslCompiledTransform myXslTrans = new XslCompiledTransform();
            //load the Xsl 
            myXslTrans.Load(sXslPath);
            //create the output stream
            XmlTextWriter myWriter = new XmlTextWriter(outputFileName, null);
            //do the actual transform of Xml
            myXslTrans.Transform(myXPathDoc, null, myWriter);
            myWriter.Close();
        }
        catch (Exception e)
        {

            EventLogger eventLog;
            eventLog = new EventLogger("transformUtil", e.ToString());
        }

    }
}

该代码有效,但输出文件的标头中没有 XML 声明。

**<?xml version="1.0" encoding="utf-8"?>**

我不知所措。当我使用相同的 XSL 文件转换 XML 时,使用 notepad++ 或 Visual Studio 之类的工具,转换包含标题中的 XML 声明。那么 XslCompiledTransform 是否负责截断此声明?我很困惑。

还有其他人面临类似问题吗?

我的 XSL 文件头看起来像这样。

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
4

1 回答 1

1

使用的 XML 编写器没有任何关联的设置。

改变

//create the output stream
XmlTextWriter myWriter = new XmlTextWriter(outputFileName, null);

XmlWriterSettings settings = 
   new XmlWriterSettings
   {
      OmitXmlDeclaration = false
   };
XmlWriter myWriter = XmlWriter.Create(outputFileName, settings);

或者,您可以少做一些设置转换:

private static void transformUtil(string sXmlPath, string sXslPath, 
                                  string outputFileName)
{
    try
    {
       XslCompiledTransform xsl = new XslCompiledTransform();

       // Load the XSL
       xsl.Load(sXslPath);

       // Transform the XML document
       xsl.Transform(sXmlPath, outputFileName);
    }
    catch (Exception e)
    {
       // Handle exception
    }

}

这也应该遵守XSLT 文件本身的xsl:outputomit-xml-declaration指令,特别是属性,如果未指定,默认值为“no”。

于 2010-11-10T02:32:50.473 回答