1

.NET Framework 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"?>**

私はこれを理解するのに途方に暮れています。notepad++ や Visual Studio などのツールを使用して、同じ XSL ファイルを使用して XML を変換すると、変換のヘッダーに 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:output命令、特にomit-xml-declaration指定されていない場合のデフォルト値が「no」である属性も尊重する必要があります。

于 2010-11-10T02:32:50.473 に答える