开发者

XSL Transformation through code does not result in the same output as XSL transformation done through a tool

I am transforming my XML file to another XML file using the XslCompiledTransform classes available in the .NET framework 3.5

Here's my code.

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

    }
}

The code works, but the output file does not have the XML declaration in the header.

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

I a开发者_如何学Pythonm at a loss to understand this. When I use the same XSL file to transform the XML, using a tool like notepad++ or visual studio, the transformation contains the XML declaration in the header. So is XslCompiledTransform responsible for truncating this declaration? I am puzzled.

Anyone else facing similar issues?

My XSL file header looks like this.

<?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="/">


The XML writer used does not have any settings associated with it.

change

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

to

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

Alternatively, you could do less to setup the transform:

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
    }

}

This should also honor the xsl:output instructions from the XSLT file itself, in particular the omit-xml-declaration attribute, for which the default value is "no" if left unspecified.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜